Sitemap

Introduction to C# Operator Overloading

2 min readApr 27, 2018

--

Have you ever wanted to use operators such as +, or *, with your custom C# object? If so, this is where you can learn the basics.

Suppose we have an object representing people like this:

public class Person
{
public string FirstName;
public string LastName;
}

Now, I want to be able to create children using two people like this:

var dad = new Person { FirstName = "Stevie", LastName = "Ray" };
var mom = new Person { FirstName = "Lucy", LastName = "Lu" };
// Create a child with Stevie and Lucy
var child = dad + mom;

Without using operator overloading you could accomplish this via a normal method as such:

public class Person {
// Properties hidden
public Person MakeChild(Person otherPerson) {
return new Person {
FirstName = otherPerson.LastName,
LastName = this.LastName
};
}
}

Then making a child could be done like:

var child = dad.MakeChild(mom);

Adding a feature like that does work, but for a reproduction operation, it feels a bit unnatural. That is where operator overloading comes into play.

Get Charles Bayley’s stories in your inbox

Join Medium for free to get updates from this writer.

To overload an operator you have to use the keyword operator followed by the operator you wish to overload. Additionally, the operator must be a method.

Lets re-implement our MakeChild operation using:

public class Person {
// Properties hidden
public static Person operator +(Person leftPerson, Person rightPerson) {
return new Person {
FirstName = rightPerson.LastName,
LastName = leftPerson.LastName
};
}
}

Now we can make children in the more natural way:

var child = dad + mom;

Dangers

There is one thing to watch out for when using operators in this way. Make sure you only use them where it really makes sense. Don’t throw them all your code just because they are cool.

Opinions

I tend to only use operators to add functionality to numeric and math based objects such as currency and vectors. I think it is, usually, better to reserve their use to places where the meaning of the operator is well known, like adding $1.27 with $13.46.

I hope you enjoyed learning about operator overloading in C#!

Working Example

--

--