Most of the built-in operators that are available in C# can be redefined. In todays article, I’ll be showing you how you can redefine operators to match your custom classes. Additionally, I’ll cover which operators actually can be overwritten.
To create custom functionality for operators in combination with your own classes, you’ll simply need to create methods matching a specific pattern. These methods require the usage of the keyword operator, followed by the actual operator you’ll want to overwrite.
I’ve created a simple class to demonstrate the concept of operator overloading. This class represents a rectangle, which only has the two properties Length and Width.
I’d like to start by overloading the + operator. When this is applied to two rectangles, I want to receive a new rectangle where both width and length from both input objects are added. You achieve this functionality by adding the following method to the class Rectangle.
Quite easy, isn’t it? But of course, you’re not restricted to these simple operators, which is why I’ll cover all of the available operators in the next section.
Another example I’d like to demonstrate is the comparison of two objects. In the following listing, you can see the comparison of two Rectangle objects with the operators == and !=.
Altough a lot of operators can be overloaded, there are some exceptions. To give you a better understanding and overview of allowed operators, I’ve listed them in the table below.
Subscribe via RSS