Information Technology Reference
In-Depth Information
Operator Overloading
The C# operators, as you've seen, are defined to work using the predefined types as operands.
If confronted with a user-defined type, the operator simply would not know how to process it.
Operator overloading allows you to define how the C# operators should operate on operands
of your user-defined types.
Operator overloading is only available for classes and structs.
You can overload an operator
x
for use with your class or struct by declaring a method
named
operator
x
that implements the behavior (e.g.,
operator +
,
operator -
, etc.).
The overload methods for unary operators take a single parameter of the
class
or
struct
type.
-
-
The overload methods for binary operators take two parameters, at least one of
which must be of the
class
or
struct
type.
public static LimitedInt operator -(LimitedInt x) // Unary
public static LimitedInt operator +(LimitedInt x, double y) // Binary
An operator overload method must be declared as
Both
static
and
public
A member of the class or struct for which it is an operand
For example, the following code shows two of the overloaded operators of a class named
LimitedInt
: the addition operator and the negation operator. You can tell that it is negation
and not subtraction because the operator overload method has only a single parameter, and is
therefore unary; whereas the subtraction operator is binary.
class LimitedInt
Return
{
Required
type
Keyword
Operator
↓
↓
↓
↓
public static LimitedInt operator +(LimitedInt x, double y)
{
LimitedInt li = new LimitedInt();
li.TheValue = x.TheValue + (int)y;
return li;
}
public static LimitedInt operator -(LimitedInt x)
{
// In this strange class, negating a value just sets its value to 0.
LimitedInt li = new LimitedInt();
li.TheValue = 0;
return li;
}