Casting to string versus calling ToString
(string)obj
castsobj
into astring
.obj
must already be astring
for this to succeed.obj.ToString()
gets a string representation ofobj
by calling theToString()
method. Which isobj
itself whenobj
is astring
. This (should) never throw(s) an exception (unlessobj
happens to benull
, obviously).
So in your specific case, both are equivalent.
Note that string
is a reference type (as opposed to a value type). As such, it inherits from object and no boxing ever occurs.
If its any help, you could use the 'as' operator which is similar to the cast but returns null instead of an exception on any conversion failure.
string str3 = obj as string;