Use of colon in C# constructor header

You can always make a call to one constructor from within another. Say, for example:

public class mySampleClass
{
    public mySampleClass(): this(10)
    {
        // This is the no parameter constructor method.
        // First Constructor
    }

    public mySampleClass(int Age) 
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}

this refers to same class, so when we say this(10), we actually mean execute the public mySampleClass(int Age) method. The above way of calling the method is called initializer. We can have at the most one initializer in this way in the method.

In your case it going to call default constructor without any parameter


It's called constructor chaining - where it's in fact calling another constructor (which takes no params in this case), and then comes back and does any additional work in this constructor (in this case setting the values of Real and Imaginary).


This is a constructor-initializer which invokes another instance constructor immediately before the constructor-body. There are two forms of constructor initializers: this and base.

base constructor initializer causes an instance constructor from the direct base class to be invoked.

this constructor initializer causes an instance constructor from the class itself to be invoked. When constructor initializer does not have parameters, then parameterless constructor is invoked.

class Complex
{
   public Complex() // this constructor will be invoked
   {    
   }

   public Complex(double real, double imaginary) : this()
   {
      Real = real;
      Imaginary = imaginary;
   }
}

BTW usually constructors chaining is done from constructors with less parameters count to constructors with more parameters (via providing default values):

class Complex
{
   public Complex() : this(0, 0)
   {    
   }

   public Complex(double real, double imaginary)
   {
      Real = real;
      Imaginary = imaginary;
   }
}

Tags:

C#

Constructor