C# FAQ: How can one constructor call another
| 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
- Are C# constructors inherited?
- How can one constructor call another?
- Are constructors the same in C++ and C#?
- Are destructors the same in C++ and C#?
- How call a virtual method from a constructor or destructor?
- How do destructors work in C#?
- How enforce constructor correctness in C#?
- How make a C# destructor virtual?
- What are the differences between C# and Java constructors?
- What are the differences between C# finalizers and Java destructors?
- What is the syntax for calling an overloaded constructor from within a constructor?
- Why must
structconstructors have at least one argument?