Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

like image 870
user544079 Avatar asked Mar 17 '11 06:03

user544079


2 Answers

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.

like image 195
Brent Stewart Avatar answered Sep 28 '22 00:09

Brent Stewart


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
}
like image 42
Andy White Avatar answered Sep 28 '22 00:09

Andy White