Classes – Constructors & Chaining

When we create a class we get given a default blank constructor which is provided by the framework. Its equivalent to

public ClassName() {}

We can create constructors with different parameters:

public ClassName(int One)
{
    this.One = One;
}
public ClassName(int One, string Two)
{
    this.One = One;
    this.Two = Two;
}

Keep in mind that c# only sees the type and order of the parameters as unique. So the following isn’t possible because they appear the same to the compiler :-

public ClassName(int One, string Two){}
public ClassName(int Three, string Four){}

N.B. When you define ANY constructor for a class the default one provided by the compiler is removed. So we have to add an empty constructor if we need one.

Chaining Constructors

Constructors often perform validation, like properties, and duplicating this can lead to errors.

This code repeats the assignment in both constructors :-

public ClassName(int One)
{
    this.One = One;
}
public ClassName(int One, string Two)
{
    this.One = One;  //this is already in the previous constructor
    this.Two =Two;
}

We can use the same principle we use when creating overridden functions and chain down to the constructor with the most parameters and keep all validation logic in there.  We call the other constructor using ‘ : this ClassName’

public ClassName() //No validation
/* these constructors chain to the main one */
public ClassName(int One) : this(One, "")
{
    //any code here runs AFTER the master constructor
}
public ClassName(string Two) : this(-1, Two)
{
    //any code here runs AFTER the master constructor
}
/* this is the master constructor that the others call */
public ClassName(int One, string Two)
{
    if (One>0) {this.One = One}
    if (Two>"") {this.Two = Two}
}

Leave a Reply

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