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
- select pwd from dbo.LoginTable where UserID='Admin'

2) With Invalid data
- select pwd from dbo.LoginTable where UserID='Test'

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()".
- private object GetValue()
- {
- //Fetch the data from the database and return it
- //1st time as in Step A shows, it will return 16d7a4fca7442dda3ad93c9a726597e4
- //2nd time as in Step A shows, it will return null
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- object result = GetValue();
- Response.Write(result.ToString());
- }

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:
- protected void Button1_Click(object sender, EventArgs e)
- {
- object result = GetValue();
- Response.Write(Convert.ToString(result)); //.ToString() to Convert.ToString()
- }

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.

Tom MohanPosted Mar 15, 2015, 6:57 AM
useful
Naveed ZamanPosted Mar 14, 2015, 10:41 AM
I like your teaching style. Nice
Shahnawaz AlamPosted Mar 14, 2015, 7:47 AM
A blog for such a small thing?
Vineet KumarPosted Mar 13, 2015, 2:02 PM
Well the .ToString() has its own uses. You can create a class and override ToString method to return a more relevant and useful value than returning the string representation of object.