C# Operator Overloading

Categories: Programming
Tags:
Comments: No Comments
Published on: July 22, 2010

C# allows programmers to overload all of the operators.

Equality ( == ) operator can be overloaded as follows:

public static bool operator ==(T item1, T Item2)
{
return item1.SomeProperty == item2.SomeProperty && item1.AnotherProperty == item2.AnotherProperty;
}

public static bool operator !=(T item1, T item2)
{
return !(item1==item2);
}

public static bool operator <(T item1, T item2)
{
return item1.SomeProperty < item2.SomeProperty;
}

etc.

Operators that can be Overloaded:

+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.

+, -, !, ~, ++, –, true, false All C# unary operators can be overloaded.

==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.

&&, || They can’t be overloaded

() (Conversion operator) They can’t be overloaded

+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.

=, . , ?:, ->, new, is, as, size of These operators can’t be overloaded

Share this

Welcome , today is Tuesday, February 7, 2012

Bad Behavior has blocked 251 access attempts in the last 7 days.