CSharp - Operator Overloading Guidelines

Introduction

Operator overloading helps us to supply special/additional meaning to an operator.

C# does not allow us to overload all the operators.

Here are the guidelines.

Operators
Overloadability
+, -, !, ~, ++, --, true, false
we can overload these unary operators.
+, -, *, /, %, &, |, ^, <<, >>
we can overload these binary operators.
==, !=, <, >, <=, >=



the comparison operators can be overloaded
If overloaded, comparison operators must be overloaded in pairs; for
example, if = = is overloaded, we need to overload != also. the reverse is also
true and it is similar for < and > and for <= and >=.
&&, ||

conditional logical operators cannot be overloaded, but they are
evaluated using & and |, which can be overloaded.
[ ]

we cannot overload the array indexing operator but we can define
indexers.
(t)x

we cannot overload the cast operator but we can define new
conversion operators (e.g., in the context of explicit and implicit)
+=, -=, *=, /=, %=, &=, |=,
^=, <<=, >>=
we cannot overload assignment operators but +=; for example, is
evaluated using +, which can be overloaded.
=, ., ?:, ??, ->, =>, f(x),
as, checked, unchecked,
default, delegate, is, new,
sizeof,typeof
we cannot overload these operators.



Related Topic