Cast Operator Overloading

Learn to add custom behavior to casting operations.


When trying to store an object of one type in a variable of another type, an implicit cast may take place. In other circumstances, we must cast an object explicitly:

int number = 14;
short secondNumber = (short)number; // Explicit cast due to shrinking
int anotherNumber = secondNumber; // Implicit cast due to expansion

It would be ideal if we could control the specificity of this casting for our user-defined types. Cast operator overloading lets us control the exact process of type casting. We can overload both implicit and explicit casts.

Custom behavior for implicit casts

Here’s the syntax for overloading the implicit cast operator:

// When Source_Type is implicitly cast into Return_Type
public static implicit operator Return_Type(Source_Type parameter)

We use the keywords, implicit operator, followed by a return type (the target type our object is cast into). We can have different cast operator overloads for different target types.

To clarify, let’s create a sample class and overload its implicit cast operator:

class BankAccount
	public decimal Funds { get; set; }

Our class has a single property that represents the amount of money in the bank account. We want the BankAccount object to be able to cast to decimal. To enable that, we create an overload that implicitly casts our BankAccount object to decimal:

Get hands-on with 1200+ tech skills courses.