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.

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.