How and when to call the base class constructor in C#
You can call the base class constructor like this:
// Subclass constructor
public Subclass()
: base()
{
// do Subclass constructor stuff here...
}
You would call the base class if there is something that all child classes need to have setup. objects that need to be initialized, etc...
Hope this helps.
It's usually a good practice to call the base class constructor from your subclass constructor to ensure that the base class initializes itself before your subclass. You use the base
keyword to call the base class constructor. Note that you can also call another constructor in your class using the this
keyword.
Here's an example on how to do it:
public class BaseClass
{
private string something;
public BaseClass() : this("default value") // Call the BaseClass(string) ctor
{
}
public BaseClass(string something)
{
this.something = something;
}
// other ctors if needed
}
public class SubClass : BaseClass
{
public SubClass(string something) : base(something) // Call the base ctor with the arg
{
}
// other ctors if needed
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With