Call One Constructor from Another in C#
I am working on an assignment for Professor Cawfis’ C#/.NET class I am taking this quarter at The Ohio State University.</plug> The assignment asks us to write a hierarchy of Tanks for a water plant. For a specific tank, we want a constructor that will take a parameter volume. But we also want to have a parameterless constructor that will create a tank with a default volume for the tanks in this system.
Here’s what we initially have:
using Liter = System.Single
namespace KyleTolle.Tanks
{
class Tank: TankBase
{
public Tank()
{
// Want this to create a tank of a default volume.
}
public Tank(Liters maximumVolume)
{
this.Volume = maximumVolume;
}
}
}
All we need to do to have the parameterless constructor create a tank with a default value is have it call the other constructor, passing in a default value for the volume. But how do we do that?
It’s simple. To call another constructor in this class, we just add a bit more code before the method’s body braces:
public TypeConstructor(): this (parameters) { }
Want to call a constructor in the base class? Just change the previous example to say “base” instead of “this”:
public TypeConstructor(): base (parameters) { }
This could be helpful if the parent class has a constructor with the desired behavior.
So to call another constructor in our Tank example, we end up with:
using Liter = System.Single
namespace KyleTolle.Tanks
{
class Tank: TankBase
{
public Tank() : this(100F)
{
// This creates a tank with a default volume.
}
public Tank(Liters maximumVolume)
{
this.Volume = maximumVolume;
}
}
}
I decided to write this post because it wasn’t immediately apparent to me how to call one constructor from another. Google did lead me to the solution, but I give a bit more concrete example of what this can be used for.