Convert.ToString vs .toString

by Edward 24 July 2009 06:38

I have seen numerous applications where developers use ".toString" to convert a value to string. However lets say you are trying to convert a value from a database field that does allow NULL to inserted... what will happen if you cast this value to a string from int?

For my examples I left the entry in the database NULL.

Example with "Convert.ToString()":

// This will set the variable test to null:
// Use a datareader to return result from database
string age = Convert.ToString(dt.Rows[i][1].ToString());

Console.WriteLine(age);

If you run this code snippet in your own code, you will see NULL is written assigned to the variable.

Example with "toString()":


// This will throw an exception:
// Use a datareader to return result from database
string age = dt.Rows[i][1].ToString();

Console.WriteLine(age);

If you run this code snippet in your own code, you will see that the code will break. The problem with this statement is that null doesn't have a ".ToString()" method. It will throw a NULL reference exception error.

To summarise, it is best practice to CONVERT a value to string, if you are not sure what value you are getting back, then to CAST it to a string.

Tags: , ,

ASP.NET | Social Media

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List