Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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 4-1 lists the available overloadable operators.

Table 4-1. 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 that the references point to.

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.

Tip

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard

Publisher Resources

ISBN: 0596005261Catalog PageErrata