# Introduction
We know very well about both.Tostring() and Convert.ToString(), which are used to convert the input as a string. For this, let's take an example to find the difference and the uses.
Uses
Both(.Tostring() and Convert.Tostring()) are used to convert the respective input to the string.
Example
- int myAge = 104;
- Console.WriteLine(".ToString() : " + myAge.ToString());
- Console.WriteLine("Convert.ToString() :" + Convert.ToString(myAge));
In the example given above, we tried to convert myAge int to string. Now, see the result, as given below.
There are no problems, so we got the result as a string and here we couldn't find the difference in an output. Let's see the difference.
Difference
Let's take one realtime seconario. In our Application, we ask the user to enter his name but he/she leaves that as null. Now, what will happen?
- string myName = null; ----------->Just assume they didn't give any input
- Console.WriteLine(".ToString() : " + myName.ToString());
- Console.WriteLine("Convert.ToString() :" + Convert.ToString(myName));
Now run the Application.
Now, we got the NullReferenceException with .ToString(); and now move to the next line. See what will happen?
Here, it accepts the null value and returns it as empty and now, we found the difference for them both, as shown below.
Convert.ToString() | .ToString() |
1. Handles NULL values even if variable value becomes null, it doesn't show the exception. | 1. It will not handle NULL values; it will throw a NULL reference exception error. |
2.We can use anytime (even null). | 2. It's only for known input(Input is not null). |
Let me present another example.
- string myName;
- object input = null;
- myName = input.ToString();
-
- myName = Convert.ToString(input);
-
I hope, it's helpful.