DotNET Schools

Blogs & Tutorials for Microsoft.NET and Leading web Technologies

Variable.ToString() vs. Convert.ToString(variable)

variable.ToString() and Convert.ToString(variable) both are used for converting data into string. But the main difference is that Convert.ToString() handles null, while ToString() doesn't handle null value.

Apart from that both works almost same. Let’s take an example to explain it:
  1. double amount = 10000.0;  
  2. Console.WriteLine(amount.ToString());  
  3. Console.WriteLine(Convert.ToString(amount));   
In this case both method will convert “amount” to string and will return the same value but in case of null value variable.ToString() method will throw exception.

Now take another example:

  1. object myObject = null;  
  2. string myString;  
  3.   
  4. //myString = myObject.ToString();  
  5. // System.NullReferenceException : { "Object reference not set to an instance of an object."}  
  6.   
  7. myString = Convert.ToString(myObject);  
  8. //return empty string