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

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.

Leave a Comment