Recently I was developing a game just to practice some design patterns and came to a point where it would be interesting to use Operator Overloading. C# is a wonderful language that allows all arithmetic and comparison operators can be overloaded.
But before we begin I feel I should explain what is Operator Overloading: Basically, it is the possibility to redefine the action of an operator. Let’s say that we want the operator + not only to add numbers but also add specific values from a user-defined type. With C# we can do that. In fact, that is what we are going to do (and some more!).
So where is how to do it using .NET Core.
First, let’s create a new Console application, just create a new folder and inside of it run the command:
dotnet new console -o OperatorOverloading
After the project is created let’s create a new Class called Point, it should have two properties: X and Y.
Now we will implement the operator overloading that will allow us to add two different points. To do so we must pay attention to some details:
- The method that will add both Points should be declared on the Point class as static.
- It has to use the word “operator” followed by the operator that is being overloaded.
- It still acts as a common method and has to specify the return type and its parameters.
Now that we overloaded our + operator we can use it, just use the command dotnet run on the updated Program.cs:
Great! we can now implement another operator overloading that will be useful for us. Now let’s make it easier to compare two Points.
This requires us to define which property will be used (or even a calculated value based on both). In my case all I needed was to compare X, so the code will be:
It is important to note that the comparison operators must be overloaded in pairs. We have to implement a boolean method for the greater-than-operator and the less-than-operator.
To test all we need to do is call it:
Below is code for the entire Point class that we implemented:
Hope you have found it useful!