;

Difference Between Convert.ToString() and .ToString() Method in C#


Tutorialsrack 10/12/2020 C#

In this article, you will learn what is the difference between Convert.ToString() and .ToString() method in C#. Both methods are used to convert a string. But, yes, there is a difference between both the method and the main difference between both the methods is that Convert.ToString() method handles the NULL whereas .ToString() method does not handle the NULL and throws a NULL reference exception.

When you use the .ToString() method, this method expects that the value must not be NULL otherwise, it will throw an error.

Here are some examples to see the difference between both methods.

Example of Convert.ToString() Method

Example of Convert.ToString() Method
using System;

namespace Tutorialsrack
{
    class Program
    {
        /* Difference Between Convert.ToString() and .ToString() Method in C# */
        static void Main(string[] args)
        {
            
            object obj1 = null;
            string str = null;

            //Convert using Convert.ToString()

            //When Object is Null
            string str1 = Convert.ToString(obj1);
            // Output ==> it will return empty string ""

            //When String is Null
            string str2 = Convert.ToString(str);
            // Output ==> it will return 'null'

            //Hit ENTER to exit the program
            Console.ReadKey();
        }
    }
}

Example of .ToString() Method

Example of .ToString() Method
using System;

namespace Tutorialsrack
{
    class Program
    {
        /* Difference Between Convert.ToString() and .ToString() Method in C# */
        static void Main(string[] args)
        {
            
            object obj1 = null;
            string str = null;

            //Convert using .ToString() Method

            //When Object is Null
            string str1 = obj1.ToString();
            // Ouptut ==> it will throw an Null reference exception

            //When String is Null
            string str2 = str.ToString();
            // Output ==> it will throw an Null reference exception

            //Hit ENTER to exit the program
            Console.ReadKey();
        }
    }
}

So, it is a good programming practice to use Convert.ToString() method over the .ToString() method. 

I hope this article will help you to understand what is the difference between Convert.ToString() and .ToString() method in C#.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags