.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.

8 Comments

  • I've also found this one real useful:



    Instead of:



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



    Use:



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



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

  • Jon, you can probably use

    ConfigurationSettings.AppSettings["Missing.Value"] as string

    as well to get null.

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



    dataReader["stringValue"].ToString()

    vs.

    Convert.ToString(["stringValue"])



    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().

  • 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.

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

  • Yes, I agree with Paresh.

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

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

Comments have been disabled for this content.