ECMA-334 C# Language Specification17.9.1: Unary operators |
The following rules apply to unary operator declarations, where T denotes the class or struct type that contains the operator declaration:
The signature of a unary operator consists of the operator token (+, -, !, ~, ++, --, true, or false) and the type of the single formal parameter. The return type is not part of a unary operator's signature, nor is the name of the formal parameter.
The true and false unary operators require pair-wise declaration. A compile-time error occurs if a class declares one of these operators without also declaring the other. The true and false operators are described further in 14.16.
public class IntVector
{
public int Length { ... } // read-only property
public int this[int index] { ... } // read-write indexer
public IntVector(int vectorLength) { ... }
public static IntVector operator++(IntVector iv) {
IntVector temp = new IntVector(iv.Length);
for (int i = 0; i < iv.Length; ++i)
temp[i] = iv[i] + 1;
return temp;
}
}
class Test
{
static void Main() {
IntVector iv1 = new IntVector(4); // vector of 4x0
IntVector iv2;
iv2 = iv1++; // iv2 contains 4x0, iv1 contains 4x1
iv2 = ++iv1; // iv2 contains 4x2, iv1 contains 4x2
}