Difference Between ToString() vs Convert.ToString() vs (string) cast
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.
Nice
nandu
November 30, 2007 at 7:04 am
Good information.
Ravi
May 20, 2008 at 7:03 am
It is Very Good
Hukam Chand
May 30, 2008 at 10:46 am
There is no difference between the 2. Convert.ToString internally uses value.ToString
Anonymous
August 21, 2008 at 7:02 am
good
Anonymous
September 17, 2008 at 3:54 am
good issue,
Bratos
January 26, 2009 at 10:51 am
Thanks…really nice to know..
Bassem
June 14, 2009 at 5:44 pm
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