Refine the complex number class in C#

Refine the complex number class

This example shows how to refine the complex number class defined by the example Make a complex number class that works with real numbers in C#. That example explains how to build a Complex class that represents complex numbers. It uses operator overloading to determine how to apply the +, -, *, and / operators to two Complex objects.

It also uses operator overloading to define operators that combine a Complex with a double and a double with a Complex. But there’s an easier way.

If you make a conversion operator to allow the program to implicitly convert a double into a Complex, then you don’t need to define operators for combining double and Complex values. When the program needs to perform that type of operation, it automatically promotes the double to a Complex and then uses the Complex operators to perform the calculation.

The following code shows this example’s double-to-Complex conversion operator.

// Double to Complex conversion.
// The implicit keyword means you don't need a cast.
public static implicit operator Complex(double real)
    return new Complex(real);

This example’s Complex class doesn’t contain all of the operators for manipulating double values so it’s simpler than the previous version.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in classes, mathematics, OOP, operators and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Refine the complex number class in C#

  1. Pingback: Use Newton's method to draw a fractal in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *