What is The Difference Between ToString() and Convert.ToString()

Most of the Students, Fresher's Faces The Question “What is The Difference Between ToString() and Convert.ToString()”.

So many times its Difficult to get Rid Of Exception While Handling Null or blank values. At That Time Its Difficult TO handle The Exception ,Or the Line From Which Exactly ,the Exception Has Thrown while handling Nulll Or Blank String Values.

As We Know String has Default Value as blank.

The Main Difference Convert.ToString()handles Null Value While “Object.ToString()” can’t.

When you Use “.Tostring()” with Null It Gives Unhandled Exception NullReference Exception
Object Reference Not Set To An Instance Of An Object”.

When You Use Convert.ToString(),Ypour Code Will Execute Successfully. You Will Not Get Any Error.

Here Is Sample Code

  1.         static void Main(string[] args)  
  2.         {  
  3.         //Throws Exception  
  4.             string strSample = null;  
  5.             string strResult =strSample.ToString();  
  6.             Console.WriteLine(strResult);  
  7.   
  8.         //Does Not Throws Exception  
  9.             string strSample = null;  
  10.             string strResult = Convert.ToString(strSample);  
  11.             Console.WriteLine(strResult);  
  12.   
  13. //Throws Exception  
  14.             string strSample = null;  
  15.             string strResult = Convert.ToString(strSample.ToString()).ToString();  
  16.             Console.WriteLine(strResult);  
  17.   
  18.         }  
Hope This blog Will Help You.