Ad

Wednesday, August 14, 2013

Difference between Convert.ToString() and ToString() method in C#.Net

Overview:
                    In this article i would like to publish an article about Difference between Convert.ToString() and ToString() method in C#.Net.


Description:
                  Convert is a Class used to convert any type of values including with null.

i.e..Convert.ToString(variable).Where as .ToString() doesnot handles null values it gives an null reference exception.So for good programming practises better to use Convert.ToString() other than .ToString()


Follwoing Program demonstrates the Difference between Convert.ToString() and ToString() method in C#.Net.


Program:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ex123
{
    class Class5
    {
        static void Main(string[] args)
        {
            try
            {
                object o = null;//For reference types we need to pass null values
                string j = Convert.ToString(o);//This method converts any values to string types
                Console.WriteLine("The Value of J is:" + j);
                string k = o.ToString();//It gives an exception becuase it wont convert null types(Null reference exception raised)
                Console.WriteLine("The Value of k is:" + k);
                Console.WriteLine("Keep Visiting this blog");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception:"+ex.Message);
            }
                Console.ReadLine();
        }
    }
}

 OutPut:
Difference between Convert.ToString() and ToString() method in C#.Net

No comments: