Tuesday, August 6, 2013

What is the main difference between .toString() and Convert.toString()? When to use which method?

“.ToString()” and "Convert.toString()"  are the major formatting methods in the .NET Framework which are used to convert an object to its equivalent string representation so that it is suitable for display or use as a string. It's important to understand the behavior and differences of both the methods to determine when to use what. Here are the differences:

Differences:

1.       “Object.ToString()” is a virtual function in the base class Object. Any class can override .ToString() to provide its own implementation whereas “Convert.ToString()” is a static method that attempts to take many different arguments and convert them into a meaningful string.
2.       The key different between both is that "Convert.toString()" function handles NULLS whereas “.ToString()” does not handles NULL values and throws a NULL reference exception when used for NULLS. So, good developers always use “Convert.toString()” which is more safer. 
3.        When “Convert.ToString()” is applied on a string value it simply returns the value while .ToString() on a sting returns this (a reference to the string itself).
4.       The “Convert.ToString()”, when called on an object will try to convert it via IConvertible interface first, if this fails and the object is not null then it will call the .ToString() on the object. If the object reference is null it returns an empty string. The default behavior of the .ToString() method on an object is to return the name of the type (this.GetType().ToString()). Calling the .ToString() method directly has less ovehead but we need to perform a null test on object first.

Here is the sample code with comments:

Object obj = null;
String objVal1 = obj.ToString(); //throws Null reference exception
String objVal2 = Convert.ToString(obj);  //returns NULL

1 comment:

  1. Hey there, You've done an incredible job.

    I'll definitely digg it and personally recommend to my friends.
    I am sure they will be benefited from this site.


    Take a look at my web site minecraft games

    ReplyDelete