Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
operator
Collapse the table of content
Expand the table of content

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.

The following is a very simplified class for 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
    */

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

Show:
© 2015 Microsoft