.ToString() vs. Convert.ToString() - Jon Galloway

.ToString() vs. Convert.ToString()

Simple tip that's saved me some time:

//This will set the variable test to null:

string test = Convert.ToString(ConfigurationSettings.AppSettings["Missing.Value"]);

//This will throw an exception:
string test = ConfigurationSettings.AppSettings["Missing.Value"].ToString();

The problem with the second statement is that null doesn't have a .ToString() method.
Either situation can be handled, but most of the time it's a lot cleaner to check for a null than to raise the exception.

Published Thursday, November 6, 2003 11:24 PM by Jon Galloway
Filed under:


# re: .ToString() vs. Convert.ToString()

I've also found this one real useful:

Instead of:

int test = Convert.ToInt32(ConfigurationSettings.AppSettings["Missing.Value"]);


int test = int.Parse(ConfigurationSettings.AppSettings["Missing.Value"]);

It will also throw an exception, which is easy to cleanly handle in a try / catch.

Friday, November 7, 2003 2:47 AM by Ken Robertson

# re: .ToString() vs. Convert.ToString()

Jon, you can probably use
ConfigurationSettings.AppSettings["Missing.Value"] as string
as well to get null.

Friday, November 7, 2003 6:35 AM by Fabrice

# re: .ToString() vs. Convert.ToString()

Right, Fabrice. Bad example, I guess - a better example might have been:


My point was that when you need to convert an object to a string and it may be null, you can do it without throwing an exception using Convert.ToString().

Friday, November 7, 2003 11:52 AM by Jon Galloway

# re: .ToString() vs. Convert.ToString()

Ya, Convert.ToString is really nice if you need a string no matter what and you don't want to create a crazy error catching system.

Friday, May 28, 2004 9:12 AM by sdfsdf

# re: .ToString() vs. Convert.ToString()

Jon you must also explain the logic behind this to us in deep also diffrence with int.parse also  

Friday, May 25, 2007 4:26 AM by Mohit

# re: .ToString() vs. Convert.ToString()

Yes, I agree with Paresh.

Friday, January 29, 2010 12:53 AM by Venu

# re: .ToString() vs. Convert.ToString()

convert.tostring() handles null but .tostring() doesn't. It will throw exception when value is null.

Tuesday, January 18, 2011 8:12 AM by shivam

# re: .ToString() vs. Convert.ToString()

you must also explain the logic behind this in deep and also diffrence with int.32 conversion.

Wednesday, January 11, 2012 12:35 AM by ashok shakya