Previous Page
Next Page

Declaring Increment and Decrement Operators

C# allows you to declare your own version of the increment (++) and decrement (––) operators. The usual rules apply when declaring these operators; they must be public, they must be static, and they must be unary. Here is the increment operator for the Hour struct:

struct Hour
{
    ...
    public static Hour operator++ (Hour arg)
    {
        arg.value++;
        return arg;
    }
    ...
    private int value;
}

The increment and decrement operators are unique in that they can be used in prefix and postfix forms. C# cleverly uses the same single operator for both the prefix and postfix versions. The result of a postfix expression is the value of the operand before the expression takes place. In other words, the compiler effectively converts this:

Hour now = new Hour(9);
Hour postfix = now++;

Into this:

Hour now = new Hour(9);
Hour postfix = now;
now = Hour.operator++(now); // pseudocode, not valid C#

The result of a prefix expression is the return value of the operator. The C# compiler effectively converts this:

Hour now = new Hour(9);
Hour prefix = ++now;

Into this:

Hour now = new Hour(9);
now = Hour.operator++(now); // pseudocode, not valid C#
Hour prefix = now;

This equivalence means that the return type of the increment and decrement operators must be the same as the parameter type.


Previous Page
Next Page