O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required