What's the difference between casting an int to a string and the ToString() method in C#

What's the difference between casting an Int to a string and the ToString() method ?

For example :-

int MyInt = 10;
label1.Text = (string)MyInt;       // This Doesn't Work
label1.Text = MyInt.ToString();    // but this does.

Solution 1:

Well, ToString() is just a method call which returns a string. It's defined in object so it's always valid to call on anything (other than a null reference).

The cast operator can do one of four things:

  • A predefined conversion, e.g. int to byte
  • An execution time reference conversion which may fail, e.g. casting object to string, which checks for the target object being an appropriate type
  • A user-defined conversion (basically calling a static method with a special name) which is known at compile-time
  • An unboxing conversion which may fail, e.g. casting object to int

In this case, you're asking the compiler to emit code to convert from int to string. None of the above options apply, so you get a compile-time error.

Solution 2:

The difference is that with the cast, you ask the compiler to assume that the int is in fact a string, which is not the case.

With the ToString(), you ask for a string representation for the int, which is in fact a string :)

Solution 3:

Um, ToString() is calling a method that returns a string representation of the integer.

When you cast, you are not returning a representation, you are saying that you want to reference the same object (well, value-type in this case) but you want to reference it as a different type.

A cast will only succeed if the type you are casting to (target type) is the same type as the object being cast or the target type is a superclass or interface of the cast object.

It is actually possible to do conversion in a cast providing the the source or target type declare implicit or explicit conversions, but the Int32 type does not do this for the String target type.