Basic Difference Between Convert.ToString() And .ToString() Method In C#

Both these methods are used to convert a string. But yes, there is a difference between them and the main difference is that Convert.Tostring() function handles the NULL while the .ToString() method does not and it throws a NULL reference exception.
So, it is a good programming practice to use Convert.ToString() method. But when you want to get an exception if you don't expect your object to be NULL, you must use the .ToString() method.



  1. //Below code will throw null reference exception. 
  2. object obj = null;  
  3. string  str = obj.ToString();  
  4.   
  5. //Below code will not throw an exception and will return String.Empty 
  6. object obj = null;  
  7. string str = Convert.ToString(obj);



I hope this clears up the basic difference between Convert.ToString() and .ToString() Method in C#.

Comments

Popular posts from this blog

Difference Between return View(), return Redirect(), return RedirectToAction() And RedirectToRoute() In MVC.

RenderBody() and RenderPage() in MVC.