If you have a child class that extends or inherits from another class, you can ensure a specific constructor in the parent class is called by using the : base() syntax as shown below.
public class Parent { public Parent() { // Empty constructor called by default } public Parent(int value) { this.Value = value; } } public class Child : Parent { public Child(int value) : base(value) { // Using the base keyword and supplying the value // parameter, ensures that the second constructor // in the Parent class is called rather than // the first } }
In the example above, when creating a new Child object, the second constructor in the Parent class will be called instead of the first. But, what if you want to call one constructor from another in the same class? Take the example below, where each constructor assigns a value to the DistanceTraveled variable.
public class Trip { public Trip(decimal distanceTraveled) { this.DistanceTraveled = distanceTraveled; } public Trip(decimal travelTime, decimal velocity) { this.DistanceTraveled = travelTime * velocity; } }
While this code works, you are updating the DistanceTraveled variable in two different places which is less than desirable from a maintenance perspective (understandably this is a trivial example but with little thought I’m sure you can think of a real world situation where this would this could cause a larger problem). It would be nice to be able to call the first constructor from the second, passing in the product of the two parameters. Using the base keyword won’t work in this situation as we want to call a constructor in the same class, not a parent class. It turns out that if we simply swap ‘base’ for ‘this’, our goal can be achieved.
public class Trip { public Trip(decimal distanceTraveled) { this.DistanceTraveled = distanceTraveled; } public Trip(decimal travelTime, decimal velocity) : this (travelTime * velocity) { // the DistanceTraveled variable is updated by a call to the first constructor } }