Tuesday, 1 January 2013

C# - Difference between Convert.tostring and .tostring() method

The basic difference between them is “Convert.ToString(variable)” handles NULL values even if variable value become null but “variable.ToString()” will not handle NULL values it will throw a NULL reference exception error.

 Example

//Returns a null reference exception for str.
string strque;
object i = null;
strque = i.ToString();
//Returns an empty string for str and does not throw an exception. 
string strque;
object i = null;
strque = Convert.ToString(i);

So as a good coding practice using “convert” is always safe.

No comments:

Post a Comment