C# Operator Overloading plus and minus Operator with example


C# Operator Overloading:-  In this article, you will learn the concept of plus operator overloading in C#, with step by step programming explanation. In this article, I simply measure the width and height of a rectangle with the help of C# operator overloading.

C# Operator overloading overview:

the purpose of this application is to create a new rectangle which will contain the dimensions of two other rectangles added together. so we could encapsulate this functionality in a method that accepts two rectangle objects as parameters and returns a new rectangle containing the sum of the two rectangles dimensions, but there is a cleaner solution which encapsulates the same functionality using C# operator overloading.

we’re going to overload the plus(+) operator for the rectangle objects, and then simply add the two rectangle objects together by implementing the plus(+) operator for this purpose once we have overloaded the plus operator for the rectangle class we will be able to simply apply the plus operator between two rectangle objects.

C# Operator Overloading Plus Operator Programming Example:

Programming explanation:

First, i create a rectangle class then define two integer public fields at the top of the class which contains the width and height dimensions of rectangle objects derived from Rectangle class. The fact that these fields of public mean their values can be accessed from code outside the rectangle class, then I create the constructor for the rectangle class the constructor have the same name as the class the rectangle constructor not return a value the constructor accept two parameters namely integer parameters to store the width and height of the rectangle within the constructor code is written to assign the parameter values to the public fields of rectangle class.

This code is used to enable the overloading of the plus operator for rectangle objects so this code will basically look like a method but in order for this code to enable operator overloading it must obey certain rules we must use the static keyword followed by the type of object we wish to return as the result for the plus operation applied between the two rectangle operands then we must follow the operator keyword and then follow the operator symbol that represents the operator we wish to overload, in this case, it is the plus operator now we want to add two objects of the rectangle type together so the operator overload method will accept two objects of type rectangle as parameters we’ll name the first parameter rect1 and the second parameter rect2.

 this code is used to implement our add operation code this code will be called when the plus operator is applied between any two objects instantiate it from the rectangle class and the code is very simple i  instantiate a new object of type rectangle in the construction of rectangle object I pass in the added width dimensions of the two rectangles passed into the operator overload method to the width parameter of the rectangle. I also pass in the added height dimension of the two rectangle objects passed to the operator overload method to the object of type rectangle that i created. once the new rectangle object has been created I simply write the code to return the new rectangle object RectResult.

this in our main method, so I first create two objects both type of rectangle the first rectangle named rect1 as a width dimension of 12 and a height dimension of 10, the second rectangle named rect2 has a width dimension of 5 and a height dimension of 2.

Then I write codes that will appropriately add these two rectangles together and create a new object of type rectangle through an addition operation so because I enabled the plus operates to be overloaded for any object of type rectangle I able to add the dimensions of rect1 direct to by simply applying the plus operator between the two rectangle objects and return a value from the operation through an object reference variable of type rectangle this rectangle object reference variable is named RectResult.

In the last, I write the code that output a simple narrative showing the addition operation applied to two rectangle objects along with the result of the add operation.

C# Operator overloading

the result is as expected the new rectangle represents a width dimension of 17 which is 12 plus 5 and a height dimension of 12 which is 10 plus 2.

C# Operator Overloading Minus Operator:

We have seen that a function can be overload in a derived class. We talk, in this case also, function overload. By this overload, we change the meaning of the function compared to the function of the base class. Operators (+, -, etc.) can also be overloaded.

However, not all operators can be overloaded (for example, operator = cannot be overload). The reason for this limitation is simple: do not make programs unnecessarily less legible, or even completely illegible.

Only some unary operators and some binary operators can be overloaded. The unary operators are those that only operate on a single operand (for example – for the change sign) while binary operators operate on two operands (for example – for the subtraction).

Operators that can be overload:

Unary operators:

  • , – , !,  ~,  ++,  —

Binary operators:

+,  – , *,  /,  %,  &,  |,  ^,  <<,  >>

Operators +=, -=, *=, /=, &&, || and new cannot be overload.

To overload, an operator, write a static function. This must be called operator followed symbol to overload. But there are also other rules:

Rules for operator overloading:

Unary operator:

  • The function redefining the operator can accept only one argument, of the type of its class.
  • It must return a value, also of its class type.

Binary operator:

  • The function must accept two arguments, the first being of the class type and the second of any type.
  • The return value can be of any type.

C# Operator Overloading Minus Operator Programming Example:

To illustrate the topic, we will write a class Hour (composed of two private fields: H for hours and M for minutes) and overload the operator – to calculate the duration, expressed in minutes, between two hours. To simplify matters, we will consider that we are staying on the same day. The static operator method – (this is the name to give to the function redefining the operator minus) accepts two-hour arguments and returns the hour difference in minutes.

As we can see in the last line of code, we can now calculate the difference of two Hour objects with a very natural syntax.

Conversion operators:

Conversion operators can also be overload. Suppose we find it useful, from a point of view of the efficiency of the programming work, of being able to write (here we want to convert the object Time of the previous example as an integer):

where n would contain the number of minutes since midnight of the object now (object of type Hour). The compiler will refuse the instruction because it does not know the rule for converting a Time object into an int. We are going to teach him …

Two types of conversion are possible: implicit conversions and explicit conversions. With explicit conversions, the programmer must explicitly mark his intention to perform such a conversion (with a cast). Implicit conversions can be more insidious and often more dangerous. These two types of conversion correspond to the implicit reserved words. and explicit.

Explicit and implicit conversions in c# operator overloading:

Explicit conversion:

int n = (int) now;

Implicit conversion

int n = now;

To be able to implicitly convert a Hour object into an int, we must write (in the Hour class) a static function which must be called operator int and which obviously returns an int, which should not be therefore not specify:

Implicit conversions can cause ambiguities that are not always obvious to predict (This is particularly the case for functions that accept an object as an argument). If the compiler arrives at conclusion that there is ambiguity in the conversion, it signals this to you with a syntax error. Consider the following example (conversion of a Time object into a character string) which does not pose no problem when passing a Time object as an argument of WriteLine (the program will display for example 10:45):

But there is ambiguity, with a syntax error, if we add (the compiler ignores whether it needs to convert a Time object in an int or a string because both forms exist as signatures of Console.WriteLine):

The ambiguity is removed by forcing explicit conversions (with the reserved word explicit instead of implicit) and forcing the programmer to write, for example:

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button