Is there a difference between the ToString method and casting to string?
There is a difference, yes. Every object has a ToString
method, but not every object can be cast to a string.
int i = 10;
string s1 = i.ToString(); // OK
string s2 = (string)i; // Compile error.
object o = 10;
string s3 = o.ToString(); // OK
string s4 = (string)o; // Runtime error.
ToString()
raises exception when the object is null
, (string)
conversion doesn't.