C# FAQ: How can one constructor call another

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How can one constructor call another?

To call one C# constructor from another, before the body of the constructor, use either:

: base (parameters)

to call a constructor in the base class; or:

: this (parameters)

to call a constructor in this class.

The following examples illustrate how to call one constructor from another.

public class Supervisor : Employee
{
   public Supervisor (int vacationDays) : base (vacationDays)
   {
      //Add more statements here.
   }
}

In the prededing example, the base class constructor is called before the constructor block is executed. The base keyword is usable with or without parameters. Any constructor parameters can be used either as part of an expression or as parameters to base.

public class Employee
{
   public Employee(int weeklyOvertime)
   {
      overtime = weeklyOvertime;
   } 
 
   public Employee (int overtimeRate, int numberHours)
      : this (overtimeRate * numberHours)
   {
      //Add more statements here.
   }
}

Are C# constructors inherited?

No. C# constructors cannot be inherited.

If constructor inheritance were allowed, then necessary initialization in a base class constructor might easily be omitted. This could cause serious problems which would be difficult to track down. For example, if a new version of a base class appears with a new constructor, your class would get a new constructor automatically. This could be catastrophic.

See also



Personal tools