object o;
Is there any difference between o.ToString()
and (string) o
?
object o;
Is there any difference between o.ToString()
and (string) o
?
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.
object.ToString()
will convert the object into a string. If object has null value then it will throw an exception because no null value has ToString()
method.
Whereas (string)object
is a unboxing process of reference type to value type.
Here an object
value is copying into new instance of string type.
If that object
is null, it will assign null value.
If you're after safe conversion from object to string just use:
string s = Convert.ToString(o);
Yes they both are very different.
string anObjectString = (string)anObject;
is a Type cast or a Type conversion would only be successful if the type conversion is a valid one
ToString()
is a method available to all the object(s) in the Framework. It is a virtual method where the default implementation returns you the Type name of the object.
We're comparing apples to oranges here..
Yes, ToString()
is a method which every type implements (since every type inherits from System.Object
which implements the method). Certain types may override this method to provide their own custom overriding implementations. A call to ToString()
should always succeed and return a string instance (although it may be null for some implementations).
var x = new AnyArbitraryObjectType();
var y = x.ToString(); // will always succeed (if ToString has not been overridden, or if it has been overridden properly)
A cast is the conversion of a given object reference to a reference typed as string. If the reference being cast is not a string, then the cast will fail.
var a = "hello";
var b = 5;
var x = (string)a; // will succeed
var y = (string)b; // will fail with InvalidCastException
basically ToString() is a function that returns a string that represents the object you applied it on.
string as a type is like an int - a primitive (in c# its an object)