C# operator overloading
C# supports operator overloading, which allows you to define operators for your own classes. Operator overloading makes it possible to use operators like +, -, *, /, ==, !=, and others on objects of your own classes in a natural way.
Here is an example of operator overloading:
class Complex { public double Real { get; } public double Imaginary { get; } public Complex(double real, double imaginary) { Real = real; Imaginary = imaginary; } public static Complex operator +(Complex a, Complex b) { return new Complex(a.Real + b.Real, a.Imaginary + b.Imaginary); } public static Complex operator *(Complex a, Complex b) { double real = a.Real * b.Real - a.Imaginary * b.Imaginary; double imaginary = a.Real * b.Imaginary + a.Imaginary * b.Real; return new Complex(real, imaginary); } public static bool operator ==(Complex a, Complex b) { return a.Real == b.Real && a.Imaginary == b.Imaginary; } public static bool operator !=(Complex a, Complex b) { return !(a == b); } }
In this example, we define a Complex
class that represents complex numbers. We define two public properties, Real
and Imaginary
, to store the real and imaginary parts of the complex number. We also define three operator overloads for the +
, *
, ==
, and !=
operators.
The +
and *
operator overloads allow us to add and multiply complex numbers in a natural way. The ==
and !=
operator overloads allow us to compare complex numbers for equality.
With these operator overloads, we can write code like this:
Complex a = new Complex(1, 2); Complex b = new Complex(3, 4); Complex c = a + b; Complex d = a * b; Console.WriteLine(c.Real + " + " + c.Imaginary + "i"); // output: 4 + 6i Console.WriteLine(d.Real + " + " + d.Imaginary + "i"); // output: -5 + 10i Console.WriteLine(a == b); // output: False Console.WriteLine(a != b); // output: True
In this example, we create two Complex
objects, a
and b
, and use the +
and *
operators to add and multiply them. We also use the ==
and !=
operators to compare them for equality.