Why To Use Convert.ToString() Over ToString()

Description

This article explains the difference between Convert.ToString() and ToString() for the object.

Content

I will explain why to use Convert.ToString() over ToString() for an object with an example. Sometimes developers get a single value from the database without an idea of the resultvalue, either it can exist or can't, so in that case the return value will have some data otherwise it will be null.

Difference

Convert.ToString() handles nulls whereas ToString() doesn't.

The following are the details of the preceding procedure.

Step 1

Suppose I have a table named "LoginTable" with a row as in the following:



Now I will execute 2 queries respectively.

1) With Valid data

  1. select pwd from dbo.LoginTable where UserID='Admin'  
And the result will be like:



2) With Invalid data
  1. select pwd from dbo.LoginTable where UserID='Test'  
And the result will be "null" like:



Step 2

I will save its returning value into a variable in my C# code. To do that I will create a new website named "Website1".



Add a button in the default page named "Default.aspx" and change the text to "Get Value".



Step 3

Write the code to get the value from the database in a function named "GetValue()".
  1. private object GetValue()  
  2. {   
  3.    //Fetch the data from the database and return it  
  4.   
  5.    //1st time as in Step A shows, it will return 16d7a4fca7442dda3ad93c9a726597e4  
  6.    //2nd time as in Step A shows, it will return null  
  7.   
  8. }  
Now write the code on the event of a button click, where something gets the value in both cases and prints it after the conversion via ToString().
  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.    object result = GetValue();   
  4.    Response.Write(result.ToString());   
  5. }  
After running the page and pressing the button, the first result it will print is as in the following:


But in the second result it will provide a System.NullReferenceException.


Now the Convert.ToString() comes into the picture. See the power of it.

Change the .ToString() to Convert.ToString() as in the following:
  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.    object result = GetValue();  
  4.    Response.Write(Convert.ToString(result)); //.ToString() to Convert.ToString()   
  5. }  
After running the page and pressing the button in the first result it will print like:


But in the second result it will not provide an exception.


Conclusion

Now you can easily explain to anyone that Convert.ToString() handles null values whereas .ToString() doesn't handle a null value.