Monday, February 2, 2009

What is the difference between .ToString(), Convert.ToString() and (string) cast

Hi All,

There is a simple difference b/w these three

--> ToString() raise exception when the object is null. What it mean when the object is null then it will raise NullReferenceException.

Example:

So in the case of object.ToString(), if object is null, it raise NullReferenceException.

--> Convert.ToString() will return empty string if the object is null

Example:
string str="";
str=Convert.ToString(object) will return empty string if the object is null.

--> (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.

No comments: