Uses Of .Tostring() And Convert.Tostring() In C#

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 
  1. int myAge = 104;  
  2. Console.WriteLine(".ToString() : " + myAge.ToString());  
  3. 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?
  1. string myName = null; ----------->Just assume they didn't give any input   
  2. Console.WriteLine(".ToString() : " + myName.ToString());  
  3. 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.
  1. string myName;  
  2. object input = null;  
  3. myName = input.ToString();  
  4. //Returns null reference exception for myName  
  5. myName = Convert.ToString(input);  
  6. //Returns empty string to myName and it will not throw the exception   
 I hope, it's helpful.