operator (C# Reference)

Use the operator keyword to overload a built-in operator or to provide a user-defined conversion in a class or struct declaration.

To overload an operator on a custom class or struct, you create an operator declaration in the corresponding type. The operator declaration that overloads a built-in C# operator must satisfy the following rules:

  • It includes both a public and a static modifier.
  • It includes operator X where X is the name or symbol of the operator being overloaded.
  • Unary operators have one parameter, and binary operators have two parameters. In each case, at least one parameter must be the same type as the class or struct that declares the operator.

For information about how to define conversion operators, see the explicit and implicit keyword articles.

For an overview of the C# operators that can be overloaded, see the Overloadable operators article.

Example

The following example defines a Fraction type that represents fractional numbers. It overloads the + and * operators to perform fractional addition and multiplication, and also provides a conversion operator that converts a Fraction type to a double type.

class Fraction
{
    int num, den;
    public Fraction(int num, int den)
    {
        this.num = num;
        this.den = den;
    }

    // overload operator +
    public static Fraction operator +(Fraction a, Fraction b)
    {
        return new Fraction(a.num * b.den + b.num * a.den,
           a.den * b.den);
    }

    // overload operator *
    public static Fraction operator *(Fraction a, Fraction b)
    {
        return new Fraction(a.num * b.num, a.den * b.den);
    }

    // user-defined conversion from Fraction to double
    public static implicit operator double(Fraction f)
    {
        return (double)f.num / f.den;
    }
}

class Test
{
    static void Main()
    {
        Fraction a = new Fraction(1, 2);
        Fraction b = new Fraction(3, 7);
        Fraction c = new Fraction(2, 3);
        Console.WriteLine((double)(a * b + c));
    }
}
/*
Output
0.880952380952381
*/

C# language specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also