Home » C# programming

What is Operator Overloading in C#?

In this article, we are going to learn about operator overloading in C#, here, we will also learn - which operators can be overloaded and which cannot be overloaded?
Submitted by IncludeHelp, on February 18, 2018

C# - Operator Overloading

It is a type of polymorphism. As we know that every operator has a pre-defined implementation. But using operator overloading we can assign some special task to c# operators with respect to user defined data-type like classes and structures.

We can overload some C# operators; all C# operators cannot be overloaded. We can overload following operators that are given below:

  1. Arithmetic operators (+ - * / %)
  2. Bitwise operators (& | << >>)
  3. Unary operators (+ - ! ~ ++ --)
  4. Relational operators (== != < > <= >=)
  5. Compound assignment (+= -= *= /= %=)

We cannot overload following operators are given below:

  1. Logical operators (&& ||)
  2. Conversion operator ( () )
  3. Assignment operator ( = )
  4. Dot or membership operator ( . )
  5. Conditional or ternary operator ( ?: )
  6. Referential operator ( -> )
  7. New operator ( new )
  8. Size of operator ( sizeof() )

In C#, to overload any allowed operator we need to use operator keyword. Here we create a method with given operator like + , - and operator keyword. This method must be public and static. This method can take only value arguments, here we cannot use ref or out parameters.

Syntax:

    public static return_type operator op (Type t)
    {
	    // Statements
    }

Here, Type must be a class or strurct.

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.