Type Conversion in C#

Type Conversion

The process of converting one type to another is called type conversion. In C#, you can perform the following kinds of conversions:

  • Implicit conversions
  • Explicit conversions
  • User-defined conversions
  • Conversion with a helper class

To go more in detail about Implicit and Explicit conversions read my previous article Boxing and Unboxing in C#.

Implicit conversions

An implicit conversion doesn’t need any special syntax, it can be executed because the compiler knows that the conversion is allowed and that it’s safe to convert.

A value type such as int can be stored as a double because an int can fit inside a double without losing any precision or from a reference type to one of its base types.

In this example, num is int and will be converted to double and no data will be lost.

int num = 123456;
double bigNum = num;
Console.WriteLine("bigNum: {0}", bigNum); 
/* Output:
    bigNum: 123456
*/

Also for reference types, no special syntax is necessary because a derived class always contains all the members of a base class. In these cases, the cast is done implicitly by the compiler.

Rectangle rectangle = new Rectangle();
Shape shape = rectangle;

Continue reading