Difference between Convert.ToString() and .ToString() in C#

Well most of us might have seen Convert.TOString() and .ToString() in C# code. Baically both are used to convert a value to a String but there is a basic difference between them. When we have an NULL object, Convert.ToString(Object); handles the NULL value but where as Object.ToString(); does not handle the NULL value and it throws NULL Reference Exception. Lets go through an example:

1
2
3
4
5
6
7
8
9
10
11
int age = 25;
string  s = age.ToString();  // age value will be converted to String
string s  = Convert.ToString(age);  // age value will be converted to string
 
// But when we have  a null value for an object
int age = 0;
string  s = age.ToString();  // age value will not be converted to String, 
//as .ToString(); will not handle the NULL values and it throws a NULL Reference Exception error.
 
string s  = Convert.ToString(age);  // age value will be converted to string, 
//as Convert.ToString(); will handle the NULL values;

So it is a Good Programming practise to use Covert.ToString() as it handles the NULL values which saves us from unnecessary debugging.

Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

Filed Under: Language Basics

Tags:

RSSComments (0)

Trackback URL

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.