Thursday, 2 June 2016

difference between Convert.ToString() and ToString() methods

Every class or struct in C# implicitly inherits the Object class. Therefore, every object in C# gets the ToString method, which returns a string representation of that object.

.ToString() does not handle null value. It gives and System.NullReferenceException.
But Convert.ToString() handles null value.
Let’s understand this difference using example: Using Convert.ToString()

using System;

namespace ConverString
{
    class Program
    {
        static void Main(string[] args)
        {
            string Test = null;

            try{
            
                //Convert class is converting base data type to another data type.
                string convertTest = Convert.ToString(Test);

                Console.WriteLine("Result: {0}",convertTest);
            }
            catch(Exception ex)
            {
                //if exception caught.
                Console.WriteLine(ex.Message.ToString());
            }
            
        }
    }
}
Output:
Result: null

Example 2: using ToString() method:

namespace ConverString
{
    class Program
    {
        static void Main(string[] args)
        {
            string Test = null;

            try{
            
                Console.WriteLine("Result: {0}", Test.ToString());
            }
            catch(Exception ex)
            {
                //if exception caught.
                Console.WriteLine(ex.Message.ToString());
            }
            
        }
    }
}
Output:
Object reference not set to instance of an object.
So you can differentiate that .ToString() method does not allow null value while Convert.ToString allows null value.

Override .ToString method

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code.
using System;

namespace ConverString
{
    class Program
    {
        static void Main(string[] args)
        {
            myClass cls = new myClass() { Name = "I am Sample." };

            Console.WriteLine(cls.ToString());
        }
    }
}

class myClass
{
    public string Name { get; set; }

    public override string ToString()
    {
        return "Hi, " + Name;
    }
}
Output:

No comments:

Post a Comment