C# Type Conversion & Casting

C# supports two types of type conversion: implicit conversion and explicit conversion (also known as casting).

Implicit Conversion

Implicit conversion occurs automatically when the compiler can safely convert a value of one type to another type without the risk of losing information or causing errors. For example, you can assign an int value to a long variable without explicit conversion, because a long can represent any value that an int can represent.

int x = 10;
long y = x;    // implicit conversion from int to long
Source:‮ww‬w.theitroad.com

In this example, the value of x is implicitly converted to a long and assigned to y.

Explicit Conversion (Casting)

Explicit conversion (casting) is required when the compiler cannot automatically convert a value of one type to another type. For example, you cannot assign a long value to an int variable without explicit conversion, because a long can represent larger values than an int.

long x = 123456789;
int y = (int)x;    // explicit conversion from long to int

In this example, the value of x is explicitly converted to an int using the cast operator (int).

C# provides several cast operators for converting between types, including:

  • (bool)
  • (byte)
  • (char)
  • (decimal)
  • (double)
  • (float)
  • (int)
  • (long)
  • (sbyte)
  • (short)
  • (uint)
  • (ulong)
  • (ushort)

Note that not all type conversions are valid, and attempting to convert incompatible types can result in run-time errors. It's important to understand the limitations and risks of type conversion, and to use casting only when necessary and with caution.