Defining Operators

The definition of an operator looks like a public static method that uses the operator keyword to indicate its specialized nature. Unary operators should take exactly one single parameter, whereas binary ones should take two. None of the parameters can be passed by reference or as an output parameter. The return type does have restrictions for certain operators, too.

For instance, consider a Vector class again. This time we define a set of useful operators:

class Vector{    private readonly int _x, _y, _z;    ...    // Whitespace is allowed between "operator" and "-".    public static Vector operator -(Vector vector)    {        return new Vector(-vector._x, -vector._y, -vector._z);    }    public ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.