Operator overloading :
C# operator definitions are class members that define or redefine the behavior of basic C# operators (called implicitly or explicitly) on instances of the class:
public class Complex
{
private double re, im;
public double Real
{
get { return re; }
set { re = value; }
}
public double Imaginary
{
get { return im; }
set { im = value; }
}
// binary operator overloading
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex() { Real = c1.Real + c2.Real, Imaginary = c1.Imaginary + c2.Imaginary };
}
// unary operator overloading
public static Complex operator -(Complex c)
{
return new Complex() { Real = -c.Real, Imaginary = -c.Imaginary };
}
// cast operator overloading (both implicit and explicit)
public static implicit operator double(Complex c)
{
// return the modulus - sqrt(x^2 + y^2)
return Math.Sqrt(Math.Pow(c.Real, 2) + Math.Pow(c.Imaginary, 2));
}
public static explicit operator string(Complex c)
{
// we should be overloading the ToString() method, but this is just a demonstration
return c.Real.ToString() + " + " + c.Imaginary.ToString() + "i";
}
}
public class StaticDemo
{
public static void Main()
{
Complex number1 = new Complex() { Real = 1, Imaginary = 2 };
Complex number2 = new Complex() { Real = 4, Imaginary = 10 };
Complex number3 = number1 + number2; // number3 now has Real = 5, Imaginary = 12
number3 = -number3; // number3 now has Real = -5, Imaginary = -12
double testNumber = number3; // testNumber will be set to the absolute value of number3
Console.WriteLine((string)number3); // This will print "-5 + -12i".
// The cast to string was needed because that was an explicit cast operator.
}
}
0 comments: