user544079
user544079

Reputation: 16639

How and when to call the base class constructor in C#

How and when to call the base class constructor in C#

Upvotes: 9

Views: 14656

Answers (2)

Andy White
Andy White

Reputation: 88475

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
}

Upvotes: 9

Brent Stewart
Brent Stewart

Reputation: 1840

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.

Upvotes: 17

Related Questions