CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
// The + operator with ints.
int a = 100;
int b = 240;
int c = a + b; // c is now 340
Once again, this is no major newsflash, but have you ever stopped and noticed how the same +
operator can be applied to most intrinsic C# data types? For example, consider this code:
// + operator with strings.
string s1 = "Hello";
string s2 = " world!";
string s3 = s1 + s2; // s3 is now "Hello world!"
In essence, the + operator functions in specific ways based on the supplied data types (strings or
integers, in this case). When the + operator is applied to numerical types, the result is the summation of
the operands. However, when the + operator is applied to string types, the result is string concatenation.
The C# language gives you the capability to build custom classes and structures that also respond
uniquely to the same set of basic tokens (such as the + operator). While not every possible C# operator
can be overloaded, many can, as shown in Table 11-1.
Table 11-1. Overloadability of C# Operators
C# Operator
Overloadability
+, -,! , ~, ++, --, true, false
These unary operators can be overloaded.
+, -, *, /, %, &, |, ^, <<, >>
These binary operators can be overloaded.
==,!=, <, >, <=, >=
These comparison operators can be overloaded. C# demands
that “like” operators (i.e., < and >, <= and >=, == and !=) are
overloaded together.
[]
The [] operator cannot be overloaded. As you saw earlier in
this chapter, however, the indexer construct provides the
same functionality.
()
The () operator cannot be overloaded. As you will see later in
this chapter, however, custom conversion methods provide
the same functionality.
+=, -=, *=, /=, %=, &=, |=, ^=, <<=,
>>=
Shorthand assignment operators cannot be overloaded;
however, you receive them as a freebie when you overload
the related binary operator.
Overloading Binary Operators
To illustrate the process of overloading binary operators, assume the following simple Point class is
defined in a new Console Application named OverloadedOps:
405