Monday, 19 September 2011

Difference Between ToString() vs Convert.ToString() vs (string) cast

There is a simple but important difference between these three…
ToString() raise exception when the object is null
So in the case of object.ToString(), if object is null, it raise NullReferenceException.
Convert.ToString() return string.Empty in case of null object
(string) cast assign the object in case of null
So in case of 
MyObject o = (string)NullObject;
But when you use o to access any property, it will raise NullReferenceException.

To anyone who says there is no difference. Yes there is:
string s;
object o = null;
s = o.ToString();
//returns a null reference exception for s.
string s;
object o = null;
s = Convert.ToString(o);
//returns an empty string for s and does not throw an exception. If you dont believe it, try it!
Neither way is right or wrong. Use the approach that applies to what behavior you need for null objects.

//This will set the variable test to null:

string test = Convert.ToString(ConfigurationSettings.AppSettings["Missing.Value"]);

//This will throw an exception:

string test = ConfigurationSettings.AppSettings["Missing.Value"].ToString();