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'
And the result will be like:
2) With Invalid data
- 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 3Write the code to get the value from the database in a function named "GetValue()".
- private object GetValue()
- {
-
-
-
-
-
- }
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().
- protected void Button1_Click(object sender, EventArgs e)
- {
- object result = GetValue();
- Response.Write(result.ToString());
- }
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:
- protected void Button1_Click(object sender, EventArgs e)
- {
- object result = GetValue();
- Response.Write(Convert.ToString(result));
- }
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.