13
object o;

Is there any difference between o.ToString() and (string) o ?

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
user496949
  • 83,087
  • 147
  • 309
  • 426

7 Answers7

20

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.
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
12

ToString() raises exception when the object is null, (string) conversion doesn't.

Soufiane Hassou
  • 17,257
  • 2
  • 39
  • 75
3

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.

mekb
  • 554
  • 8
  • 22
Sukhjeevan
  • 3,074
  • 9
  • 46
  • 89
3

If you're after safe conversion from object to string just use:

string s = Convert.ToString(o);
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
0

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..

abhilash
  • 5,605
  • 3
  • 36
  • 59
0

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
Adam Ralph
  • 29,453
  • 4
  • 60
  • 67
0

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)

Himberjack
  • 5,682
  • 18
  • 71
  • 115