C# – Proper way to accomplish this construction using constructor chaining

ccomplex-numbersconstructorconstructor-chaining

I have an assignment for my first OOP class, and I understand all of it including the following statement:

You should create a class called ComplexNumber. This class will contain the real and imaginary parts of the complex number in private data members defined as doubles. Your class should contain a constructor that allows the data members of the imaginary number to be specified as parameters of the constructor. A default (non-parameterized) constructor should initialize the data members to 0.0.

Of course I know how to create these constructors without chaining them together, and the assignment does not require chaining them, but I want to as I just like to.

Without chaining them together, my constructors look like this:

class ComplexNumber
{
    private double realPart;
    private double complexPart;

    public ComplexNumber()
    {
         realPart = 0.0;
         complexPart = 0.0
    }

    public ComplexNumber(double r, double c)
    {
         realPart = r;
         complexPart = c;
    }
    // the rest of my class code...
}

Best Answer

Is this what you're looking for?

public ComplexNumber()
    : this(0.0, 0.0)
{
}

public ComplexNumber(double r, double c)
{
     realPart = r;
     complexPart = c;
}