In C# both Convert.ToString() and ToString() methods are used to convert any given object to string variable. But to decide which one we have to use whenever we require to convert a object to string is a typical job.
Today we discuss about what are the differences between Convert.ToString() and Tostring() to convert any object to string. As I said both are used to convert the object to string, but there is a small difference is there between them. Tostring() method tries convert any object to string without data validation whereas Convert.ToString() method converts object to string if that object is not null.
Lets discuss both with simple example. As shown below we have object with null value, when we are assigning the object to some string variable by converting to string by using ToString() method we will get run-time error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharpApp
{
class Program
{
static void Main(string[] args)
{
object obj = null;
string str = obj.ToString();
}
}
}
If you execute the above program we will get below error.
Here we are getting error as "object reference not set to an instance of an object", this is because we are trying to convert null value to string by using ToString() method.
Now try to convert same null object by using Convert.ToString() method as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharpApp
{
class Program
{
static void Main(string[] args)
{
object obj = null;
string str = Convert.ToString(obj);
}
}
}
If you run the above program, we will not get any error because Convert.ToString() method skip the null values. So if you try to convert the null values to string by using COnvert.ToString() the output value is empty because there is no value for null.
As per our discussion it is better to use Convert.ToString() method to convert the any object or any variable to string as compared with the ToString() method.