[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.