object obj = "Hello";
string str1 = (string)obj;
string str2 = obj.ToString();
What is the difference between (string)obj
and obj.ToString()
?
ToString is a method defined in the Object class, which is then inherited in every class in the entire framework. The ToString method in the String class has been overwritten with an implementation that simply returns itself. So there is no overhead in calling ToString() on a String-object.
Object. ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.
Both these methods are used to convert a string. But yes, there is a difference between them and the main difference is that Convert. Tostring() function handles the NULL while the . ToString() method does not and it throws a NULL reference exception.
In Java, toString creates a new string fully disconnected from the object (and there's no other way because of immutability). The same holds e.g., for Collection#toArray , while Arrays#asList returns a view of the array, which is bidirectionally connected (mutating the array changes the list and vice versa).
(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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With