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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.