Convert.ToString() vs ToString()

Posted by vishalneeraj-24503 under ASP.NET category on | Points: 40 | Views : 2435
Here, i am going to explain difference between Convert.ToString() and ToString()

-> It handles null values and does not throw an Error, if the passed value is null.

-> It throws Exception if the passed value is null.

We can understand this by following example :-

string value1 = null;
string value2 = string.empty;

//1st Case
value2 = Convert.ToString(value1);

//2nd Case
value2 = value1.ToString();
Console.WriteLine("output of value2 is : " +value2);

In 1st case,
When we put break point then if cursor comes in value2 line then value2 will show null.
means it will not throw any error.

In 2nd case
When cursor comes in value2 line then it throws en error saying "Object Reference Not Set To An Instance Of An Object" and cursor will not go in next line.

So, better approach always write
while doing type-casting.
Because Convert.ToString is a safe.

Comments or Responses

Login to post response