Difference Between Convert.ToString and ToString Method in C#

Convert.ToString and ToString Method in C#

Both of these methods convert a value to a string. Convert. ToString() method handles null whereas the ToString() doesn’t handle null.

Let’s understand with the help of an example.

using System;
namespace UnderstandingToStringMethod
{
    public class Program
    {
        public static void Main()
        {
            Employee E1 = null;
            E1.ToString();
            Console.ReadLine();
        }
    }
    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

When running the application, it will give the error below

This is because the ToString() method in C# expects the object it is invoking to not be NULL.  C1 in our example object is Null and we are invoking ToString() on a NULL object, so we can get a NULL Reference exception.

Let see another example.
using System;
namespace UnderstandingToStringMethod
{
    public class Program
    {
        public static void Main()
        {
            String Name = null;
            Name.ToString();
            Console.ReadLine();
        }
    }
}

When we run the code, we get the same NULL Reference Exception as shown below.

This is due to tthe Name variable is null and we are using the ToString() method.

Let’s understand the Convert.Tostring()  method with help of example.

using System;
namespace UnderstandingToStringMethod
{
    public class Program
    {
        public static void Main()
        {
            Employee E1 = null;
            Convert.ToString(E1);
            String Name = null;
            Convert.ToString(Name);
            Console.WriteLine("No Error");
            Console.ReadLine();
        }
    }
    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Run the application, and it should run without error. The Convert. ToString() method handles null, whereas the ToString() method does not and throws an exception. So it is always good practice to use  Convert.ToString() which will handle the Null value.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories