Reputation: 16555
object obj = "Hello";
string str1 = (string)obj;
string str2 = obj.ToString();
What is the difference between (string)obj
and obj.ToString()
?
Upvotes: 45
Views: 47722
Reputation: 8339
(string)obj
casts obj
into a string
. obj
must already be a string
for this to succeed.obj.ToString()
gets a string representation of obj
by calling the ToString()
method. Which is obj
itself when obj
is a string
. This (should) never throw(s) an exception (unless obj
happens to be null
, 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.
Upvotes: 51
Reputation: 1108
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;
Upvotes: 18
Reputation: 1149
ToString() is object class method (the main parent class in .net) which can be overloaded in your class which inherits from object class even if you didn't inherited from it.
(string) is casting which can be implemented in the class it self, the string class so you don't have ability on it.
Upvotes: 1
Reputation: 13138
(string)obj cast the object and will fail if obj is not null and not a string.
obj.ToString() converts obj to a string (even if it is not a string), it will fail is obj is null as it's a method call.
Upvotes: 2
Reputation: 137128
At the most basic level:
(string)obj
will attempt to cast obj
to a string
and will fail if there's no valid conversion.
obj.ToString()
will return a string
that the designer of obj
has decided represents that object. By default it returns the class name of obj
.
Upvotes: 9