Search⌘ K
AI Features

Cast Operator Overloading

Explore how to implement cast operator overloading in C# to manage implicit and explicit type conversions for your custom classes. Understand when and how to define these operators to ensure safe and predictable casting between user-defined types and built-in types.

An implicit cast may occur when storing an object of one type in a variable of another type. In other cases, we must cast an object explicitly.

int number = 14;
short secondNumber = (short)number; // Explicit cast due to narrowing (shrinking)
int anotherNumber = secondNumber; // Implicit cast due to widening (expansion)
Casting built-in types
  • Line 2: We explicitly cast an int to a short because short has a smaller range, risking data loss.

  • Line 3: We implicitly cast secondNumber back to an int because int is larger and can safely hold any short value.

We can define custom casting behavior for our user-defined types using cast operator overloading. This feature allows us to control the exact process of type conversion. We can overload both implicit and explicit casts. ...