O'Reilly logo

C# Language Pocket Reference by Ted Neward, Ben Albahari, Peter Drayton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Operator Overloading

C# lets you overload operators to work with operands that are custom classes or structs using operators. An operator is a static method with the keyword operator preceding the operator to overload (instead of a method name), parameters representing the operands, and return types representing the result of an expression. Table 1-3 lists the available overloadable operators.

Table 1-3. Overloadable operators

+

-

!

~

++

--

* (binary only)

/

%

& (binary only)

|

^

<<

>>

==

~=

>

<

>=

<=

Literals that also act as overloadable operators are true and false.

Implementing Value Equality

A pair of references exhibit referential equality when both references point to the same object. By default, the == and != operators will compare two reference-type variables by reference. However, it is occasionally more natural for the == and != operators to exhibit value equality, whereby the comparison is based on the value of the objects to which the references point.

Whenever overloading the == and != operators, you should always override the virtual Equals method to route its functionality to the == operator. This allows a class to be used polymorphically (which is essential if you want to take advantage of functionality such as the collection classes). It also provides compatibility with other .NET languages that don't overload operators.

Note

A good guideline for knowing whether to implement the == and != operators is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required