C# – Operator Overloading

In this article, we will discuss about operator overloading in C#.

Table of Contents

  • Problem/ Scenario
  • Background
  • The Complete list of Operators that can be overloaded
  • The operator which cannot be overloaded
  • explanation about the code
  • Conclusion

Problem/ Scenario

We want to calculate area of square using Operator Overloading. Consider we have tow different squares . Both squares length and width different.We have to calculate total area of two squares.square
 

 
 
  
 

Fig: Squares

Background:
Operator overloading is very Like Method Overloading. All operator Overloading methods are static methods of the class. Operator will be used between objects of class. Here, I am going to use console Application of visual studio.

The Complete list of Operators that can be overloaded are:

  • Unary Operator : +,-,!,~,++,–,true,false
  • Binary Operator :+,-,*,/,%,&,|,^,<<,>>,==,!=,>,<,>=,<=

The operator which cannot be overloaded
=,&&,||,?:,Cheeked, new, typeof, as, and is operator.

Now we will create Square class. Below is the following codes.

Let’s get explanation about the code:

Here, square is the class name.

There are two property of Square Class. One is Length which has decimal data type. And other is width which has decimal type.

The above method implements the Multiplication operator (*) for a user-defined class Square. This method is a static method which have tow parameter. Both are Square’s class objects and both objects done multiplication.

We have Multiplication Length and Width.

Now we will call Square class in Main function:

Let’s get explanation about the code:

We have calculated total area of two squares.

We have create object which name given _obje1. We have assigned length of square 40 and  width of square 40

Again, we have create object which name given _obje2. We have assigned length of square 50 and other width of square 50.

New Object have been created for multiplication two object.

The Area method have been called and assigned result to area variable.

34324

 

 

 

 

 

Conclusion:

Now we are done as we have calculated amount of two Squares. Above picture shown result of amount.

Hope this will be helpful 🙂

Leave a Reply

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