operator keyword (C# Conversion Keywords)

The operator keyword is used to overload a built-in operator or to provide a user-defined conversion in a class or struct declaration.

Example: The following example 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 iNum, iDen;
public Fraction(int iNum, int iDen)
{
this.iNum = iNum;
this.iDen = iDen;
}

// overload operator +
public static Fraction operator +(Fraction x, Fraction y)
{
return new Fraction(x.iNum * y.iDen + y.iNum * x.iDen, x.iDen * y.iDen);
}

// overload operator *
public static Fraction operator *(Fraction x, Fraction y)
{
return new Fraction(x.iNum * y.iNum, x.iDen * y.iDen);
}

// user-defined conversion from Fraction to double
public static implicit operator double(Fraction oFraction)
{
return (double)oFraction.iNum / oFraction.iDen;
}
}

class Test
{
static void Main()
{
Fraction x = new Fraction(1, 2);
Fraction y = new Fraction(3, 7);
Fraction z = new Fraction(2, 3);
Console.WriteLine((double)(x * y + z));
}
}

/*Output: 0.880952380952381*/

1 comment: