What is the difference between Convert.toString and .toString()

Answered What is the difference between Convert.toString and .toString()

All Replies

  • Friday, November 03, 2006 7:57 PM
     
     Answered
    Just to give an understanding of what the above question means seethe below code.
    int i =0;
    MessageBox.Show(i.ToString());
    MessageBox.Show(Convert.ToString(i));
    We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what’s the difference.
    The basic difference between them is “Convert” function handles NULLS while “i.ToString()”
    does not it will throw a NULL reference exception error. So as good coding practice using
    “convert” is always safe.
  • Saturday, November 04, 2006 1:33 PM
     
     Answered
    Hi

    There is no difference between i.ToString() and Convert.ToString(i).

    This is the body of the Convert method:

    public static string ToString(int value)
    {
        return value.ToString();
    }

    Furthermore, the integer variable cannot be null since its a value type.

  • Tuesday, November 07, 2006 12:00 PM
     
     

     Kuju wrote:
    Hi

    There is no difference between i.ToString() and Convert.ToString(i).

    This is the body of the Convert method:

    public static string ToString(int value)
    {
        return value.ToString();
    }

    Furthermore, the integer variable cannot be null since its a value type.

    Kuju is absolutely correct.But what will happen if tostring is to be used with an custom object

  • Tuesday, November 07, 2006 9:16 PM
     
     Proposed Answer
    Once again using the trusty reflector,  the body of the Convert.ToString(object value)looks like this:

    public static string ToString(object value, IFormatProvider provider)
    {
        IConvertible convertible = value as IConvertible
        if(convertible != null)
        {
           return convertible.ToString(provider)
        }
        if(value != null)
        {
           return value.ToString();
        }
        return string.Empty
    }


    Therefore, when you try Convert.ToString() on a custum object, you are guaranteed not to get an ObjectReferenceNullException. On the other hand you might want to get an exception if you don't expect your object to be null.


    • Proposed As Answer by RamakrishnanRS Thursday, February 24, 2011 6:50 AM
    •  
  • Friday, February 22, 2008 9:43 AM
     
     

    The difference between Convert.ToString and .ToString() as follows

     

    Convert.ToString wont allow null values. Cannot convert null to String

     

    Whereas   .ToString accepts null values

     

    Thanks,

    Srinivasan.K

    Sybrant Technologies Pvt. Ltd.,

     

     

  • Friday, June 13, 2008 2:53 PM
     
     Proposed Answer
    Srini,

    i think its the other way round
    • Proposed As Answer by Pradeep Agrawal Monday, December 14, 2009 3:06 PM
    •  
  • Monday, December 14, 2009 3:07 PM
     
     Proposed Answer

    Offcourse there is a difference:

    string s;
    object o = null;
    s = o.ToString();
    //returns a null reference exception for s.

    string s;
    object o = null;
    s = Convert.ToString(o);
    //returns an empty string for s and does not throw an exception.

    • Proposed As Answer by Sh2awa Friday, May 03, 2013 11:35 PM
    •  
  • Friday, January 15, 2010 4:08 PM
     
     
    Just to give an understanding of what the above question means seethe below code.
    int i =0;
    MessageBox.Show(i.ToString());
    MessageBox.Show(Convert.ToString(i));
    We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what’s the difference.
    The basic difference between them is “Convert” function handles NULLS while “i.ToString()”
    does not it will throw a NULL reference exception error. So as good coding practice using
    “convert” is always safe.

    Muhammed Adnan is absolutely correct, so I think it is better using Convert.ToString() than using ToString()...
  • Wednesday, December 22, 2010 9:14 AM
     
     
    Muhammed Adnan is correct. 
  • Wednesday, May 25, 2011 5:30 AM
     
     

    int number =0;
    string strFirst=
    number.ToString();
    string strSecond=Convert.ToString(
    number );

    Here We can convert the integer “
    number” using “number.ToString()” or “Convert.ToString(number)” . But only the difference between them is “Convert” function handles NULLS while “number.ToString()”
    does not handle. It will throw a NULL reference exception error. So as for good programming practice using “Convert” is always safe.

     

    Muhammed Adnan is correct.

    Thanks

  • Monday, September 05, 2011 4:27 AM
     
     

     (1)  ToString() is a method present in the Object class of the System namespace.

    Now, Object class is the ultimate base class for all classes in the .NET Framework.So, whenever we create a new class (like Class1), it implicitly extends Object. And it also inherits the ToString() method.

     

             namespace  N1

             {

                           class Class1 : Object                  // implicitly

                           {

                                                                          // inherits the ToString() method

                            }

              }

     

    Now, to access the ToString() method in client code, 

     

                  Class1 obj = new Class1();                // create an instance of Class1

                 Console.WriteLine(obj.ToString());    // call the ToString() method 

                                                                        // We can wrap it in Console.WriteLine() because it returns a string

     

    We get the output as :  N1.Class1

    Thus ToString() method returns a fully qualified name of the type of the object.

    However, we get an error (exception) if we invoke ToString() on a null reference.

     

                Class1 obj = null;                               // obj holds a null value

                Console.WriteLine(obj.ToString());      

    We get a null reference exception because we cannot invoke an instance method on a null reference.

    In other words  "ToString() method does not handle nulls"

     

    (2) Convert.ToString() is a static method present in the static class Convert. BTW, it also extends Object, and inherits the ToString() method.

    The Convert class overloads the ToString() method with a set of static methods.

    For example, to invoke the ToString(obj), we say:

                       Console.WriteLine(Convert.ToString(obj));   // Convert is a static class, we use the class name to invoke the ToString() method

    On executing the above code, the object value is checked for null reference. If it is null, String.Empty is returned. Otherwise, the ToString() method of the Object class is called.

    In other words,   "Convert.ToString() handles nulls"

     

     

     

     

     


    • Edited by B.Ganesh Monday, September 05, 2011 4:28 AM
    •  
  • Thursday, October 13, 2011 12:48 PM
     
     

     ToString() vsConvert.ToString()

    We can convert the integer “variable” using “variable.ToString()” or “Convert.ToString” so what is the
    difference. The basic difference between them is “Convert” function handles NULLS while
    “variable.ToString()” does not it will throw a NULL reference exception error. So as a good coding
    practice using “convert” is always safe.

     

    Session["your_variable"] ="cheater";

    Response.Write(Convert.ToString(Session["your_variable"])); //it will display "cheater"

    Response.Write(Session["your_variable"].ToString());//it will display "cheater"

     

     //ERROR will not come in above statement because sesssion contain value



    Session["your_variable"] = null;

    Response.Write(Convert.ToString(Session["your_variable"])); //it will convert to blank value ,No erro will come

    Response.Write(Session["your_variable"].ToString());//will not handle the NULL values and it throws a NULL Reference Exception error

  • Tuesday, January 08, 2013 6:57 AM
     
     

    Hi Srini,

    you have just made a mistake by answaring the question in.

    your ans is:

    Convert.ToString wont allow null values. Cannot convert null to String

     

    Whereas   .ToString accepts null values

    but the correct ans is:

    Convert.ToString(str) automatically handle null reference Exception where as if you are using str.ToString(), you need to handle Exception by your code..

    You can try the sample code given below

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

    namespace DifBTConvertToStringAndToStringExample
    {
        class Program
        {
            static void Main(string[] args)
            {
                string   iStr=null;
                //throw exception so need to have try catch
                try
                {
                    iStr.ToString();// will cause a null ref exception
                    throw new Exception("Null ref exe");
                }
                // will not through any exception
                catch (Exception ex)
                {

                    Console.WriteLine(ex.StackTrace);
                }
                finally
                {
                    Console.WriteLine("I'll be executed in any case"+Convert.ToString(iStr));
                }
            }
        }
    }

  • Saturday, January 26, 2013 1:44 PM
     
     
    Convert.ToString() handles null, while ToString() doesn't.

    PHIJO MP

  • Monday, March 25, 2013 1:34 PM
     
     

    These reason i know.But any difference rather than this.

    Why they are introducing .ToString(); IF any reason.

  • Monday, March 25, 2013 1:38 PM
     
     

    No sir difference is there.without difference why there are introducing both.only one is enough.Some thing big difference. plz if u know means let me explain one suitchivation.

    Not a below reason.

    string strValue=nulll;

    string valu1=stValue.ToString(); //here is it will return nulllexpection

    string vale2=Convert.ToString(strVlaue); //here is it will return null or empty

  • Sunday, March 31, 2013 4:14 AM
     
      Has Code

    The basic difference between them is “Convert.ToString(variable)” handles NULL values even if variable value become null but “variable.ToString()” will not handle NULL values it will throw a NULL reference exception error. So as a good coding practice using “convert” is always safe.

    //Returns a null reference exception for str.
    string str;
    object i = null;
    str = i.ToString();
    
    //Returns an empty string for str and does not throw an exception. If you dont
    string str;
    object i = null;
    str = Convert.ToString(i);

    Source : Here

  • Wednesday, April 10, 2013 10:31 AM
     
     
    public static string ToString(object value, IFormatProvider provider)
    {
        IConvertible convertible = value as IConvertible
        if(convertible != null)
        {
           return convertible.ToString(provider)
        }
        if(value != null)
        {
           return value.ToString();
        }
        return string.Empty
    }


    Therefore, when you try Convert.ToString() on a custum object, you are guaranteed not to get an ObjectReferenceNullException. On the other hand you might want to get an exception if you don't expect your object to be null.
    • Proposed As Answer by Sudeep.A Monday, May 13, 2013 7:09 AM
    • Unproposed As Answer by Sudeep.A Monday, May 13, 2013 7:09 AM
    •  
  • Monday, May 13, 2013 7:10 AM
     
     

    string str;
    object o = null;
    str = o.ToString();//returns a null reference exception for string  str.

    string str;
    object o = null;
    str = Convert.ToString(o);//returns an empty string for string str and does not throw an exception.,it's better to use convert.tostring for good coding 



    • Edited by Sudeep.A Monday, May 13, 2013 7:11 AM
    • Edited by Sudeep.A Monday, May 13, 2013 7:11 AM
    •