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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.