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.
We'll cover the following...
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)
Line 2: We explicitly cast an
intto ashortbecauseshorthas a smaller range, risking data loss.Line 3: We implicitly cast
secondNumberback to anintbecauseintis larger and can safely hold anyshortvalue.
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. ...