The operator keyword is used to declare an operator in a class or struct declaration. An operator declaration can take one of the following four forms:
public static result-type operator unary-operator ( op-type operand ) public static result-type operator binary-operator ( op-type operand, op-type2 operand2 ) public static implicit operator conv-type-out ( conv-type-in operand ) public static explicit operator conv-type-out ( conv-type-in operand )
where:
The first two forms declare user-defined operators that overload built-in operators. Note that not all the built-in operators can be overloaded (see Overloadable Operators). At least one of op-type and op-type2 must be the enclosing type (that is, the type of which the operator is a member). This prevents redefining the integer addition operator, for instance.
The last two forms declare conversion operators. Exactly one of conv-type-in and conv-type-out must be the enclosing type (that is, a conversion operator can only convert from its enclosing type to some other type, or from some other type to its enclosing type).
Operators can only take value parameters, not ref or out parameters.
Any operator declaration can be preceded by an optional attribute list.
For more information, refer to CLR 10.9 Operators.
The following is an extremely simplified class for rational numbers. It overloads the + and * operators to perform fractional addition and multiplication, and also provides an operator that converts fractions to doubles.
using System; 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); } // define operator double public static implicit operator double(Fraction f) { return (double)f.num / f.den; } } class Test { public 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)); } }
0.88095238095238093