BLOG.CSHARPHELPER.COM: Refine the ComplexNumber class in C#
Refine the ComplexNumber class in C#
The example Extend the complex number class to work with real numbers in C# explains how to build a ComplexNumber class that represents complex numbers. It uses operator overloading to determine how to apply the +, -, *, and / operators to two ComplexNumber objects.
It also uses operator overloading to define operators that combine a ComplexNumber with a double. There's an easier way.
If you make a conversion operator to allow the program to implicitly convert a double into a ComplexNumber, then you don't need to define operators for combining doubles and ComplexNumbers. When the program contains such an expression, it automatically promotes the double to a ComplexNumber and then uses the ComplexNumber operators to perform the calculation.
The following code shows this example's double-to-ComplexNumber conversion operator.
// Double to Complex conversion. // The implicit keyword means you don't need to use an explicit cast. public static implicit operator Complex(double real) { return new Complex(real); }
This example's ComplexNumber class doesn't contain all of the operators for manipulating doubles so it's simpler than the previous version.
Comments