9

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

user544079
  • 16,109
  • 42
  • 115
  • 171
  • possible duplicate of [Calling base constructor in c#](http://stackoverflow.com/questions/12051/calling-base-constructor-in-c) and [C# Calling Base Class Constructor](http://stackoverflow.com/questions/4212624/c-calling-base-class-constructor) – Ben Voigt Mar 17 '11 at 06:09

2 Answers2

17

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.

Brent Stewart
  • 1,830
  • 14
  • 21
  • 6
    You can also call the base class constructor like this: `public Subclass() {}` -- this has exactly the same behavior as your example. – Ben Voigt Mar 17 '11 at 06:16
9

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
}
Andy White
  • 86,444
  • 48
  • 176
  • 211
  • 7
    It's not just a good practice, it's a requirement enforced by the compiler. [A base constructor will get called whether you like it or not.](http://stackoverflow.com/questions/3265958/how-can-i-tell-the-inheriting-class-to-not-call-its-base-class-parameter-less-co) – Ben Voigt Mar 17 '11 at 06:15
  • 1
    Good point... it will call the default ctor if you don't explicitly call a specific ctor. – Andy White Mar 17 '11 at 06:16
  • In Flash/AS3, you could do work in the subclass constructor, then call "super()" partway though to run the base class constructor, then continue with more code in the subclass constructor. In C#, you're forced to call the base class constructor first, before any code in the subclass constructor runs. – Triynko Jan 22 '16 at 19:51
  • There is a sort of workaround however. If you make a virtual method in the base class, and override it in your subclass, then you can put the code you need to run in the overridden method and call it from the base class. – Triynko Jan 22 '16 at 19:57