• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

Operator Overloading in C# .Net

Operator Overloading

 

int a = 10; b = 20;,c;

C= a + b-arrrow30  (Addition)

String S1 = ‘ABC’, S2 = ‘XYZ’,S3;

S3 = S1+S2arrrowAbc xyz  (concatenation)

Assume that test is a class and t1,t2,t3 are objects then

T3 = t1+t2 gives an error

‘+’ operator is developed to use with numbers and string only BUT NOT WITH OBJECTS.

 

Operator overloading is a concept of extending the functionality of an Existing operator.

All the operators are over loadable except those contains a.

That is the following operators are not over loadable.

 

arrrow  member Access operator

:: Ternary or conditional operator

:: property access operator

:   Inheritance operator

While overloading relational operators, these must be overloaded in ‘PAIR’.

 

To overload >, < must be overloaded

To overload >=, <= must be overloaded.

To overload ==,!= must be overloaded.

 

Overloaded operator must be declared as static.

Operators is a keyword.

Syntax to overloaded an operator

 

Public static return type  operator + (args)

{

Logic;

}

 

Example :-  on overloading + operator for adding the objects

 

Class EMP

{

Private int Sal;

.

.

.

.

}

E1  arrrow Sal (5000)

E2 arrrow Sal (8000)

E3   arrrow Sal (2700)

 

E1+E2+E3 = EMP(Data type)

 

Open windows forms Application project à Place a button arrrow Code in GD

 

Class EMP

{

Private int Sal;

Public EMP (int x  )// constructor

{

Sal = X;

}

Public EMP () // Default constructor

{}

Public void Print ()

{

Message Box. Show (Sal);

}

 

//overloading  + public static EMP operator  +  (EMP X , EMP y)

{

EMP t = new EMP ();

Sal = X. Sal + Y. Sal;

return t;

} operator overloading

 

}// EMP class

 

Code for Button 1_click

{

EMP e1 = new EMP (5000);

EMP e2 = new EMP (8000);

EMP e3 = new EMP (5000);

EMP total  = new EMP ();

Total = e1 +e2+e3 ;

Total .Print ();

}

 

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on Operator Overloading in C# .Net"

    Leave a Message

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

    Site Disclaimer, Copyright © 2016 - All Rights Reserved.

    Support


    Please leave a message and we'll get back to you soon.

    I agree to be contacted via e-mail.