Manish Pansiniya’s Blog

.NET, C#, Javascript, ASP.NET and lots more…:)

Difference Between ToString() vs Convert.ToString() vs (string) cast

with 8 comments

There is a simple but important difference between these three…

ToString() raise exception when the object is null

So in the case of object.ToString(), if object is null, it raise NullReferenceException.

Convert.ToString() return string.Empty in case of null object

(string) cast assign the object in case of null

So in case of
MyObject o = (string)NullObject;

But when you use o to access any property, it will raise NullReferenceException.

 

Written by Manish

October 8, 2007 at 1:16 pm

Posted in .NET, .NET 3.0

8 Responses

Subscribe to comments with RSS.

  1. Nice

    nandu

    November 30, 2007 at 7:04 am

  2. Good information.

    Ravi

    May 20, 2008 at 7:03 am

  3. It is Very Good

    Hukam Chand

    May 30, 2008 at 10:46 am

  4. There is no difference between the 2. Convert.ToString internally uses value.ToString

    Anonymous

    August 21, 2008 at 7:02 am

  5. good

    Anonymous

    September 17, 2008 at 3:54 am

  6. good issue,

    Bratos

    January 26, 2009 at 10:51 am

  7. Thanks…really nice to know..

    Bassem

    June 14, 2009 at 5:44 pm

  8. To anyone who says there is no difference. Yes there is:
    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. If you dont believe it, try it!

    Neither way is right or wrong. Use the approach that applies to what behavior you need for null objects.

    mr johnson

    October 30, 2009 at 6:54 am


Leave a Reply