In C#, do you need to call the base constructor?

Solution 1:

You do not need to explicitly call the base constructor, it will be implicitly called.

Extend your example a little and create a Console Application and you can verify this behaviour for yourself:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass foo = new MyClass();

            Console.ReadLine();
        }
    }

    class BaseClass
    {
        public BaseClass()
        {
            Console.WriteLine("BaseClass constructor called.");
        }
    }

    class MyClass : BaseClass
    {
        public MyClass()
        {
            Console.WriteLine("MyClass constructor called.");
        }
    }
}

Solution 2:

It is implied, provided it is parameterless. This is because you need to implement constructors that take values, see the code below for an example:

public class SuperClassEmptyCtor
{
    public SuperClassEmptyCtor()
    {
        // Default Ctor
    }
}

public class SubClassA : SuperClassEmptyCtor
{
    // No Ctor's this is fine since we have
    // a default (empty ctor in the base)
}

public class SuperClassCtor
{
    public SuperClassCtor(string value)
    {
        // Default Ctor
    }
}

public class SubClassB : SuperClassCtor
{
    // This fails because we need to satisfy
    // the ctor for the base class.
}

public class SubClassC : SuperClassCtor
{
    public SubClassC(string value) : base(value)
    {
        // make it easy and pipe the params
        // straight to the base!
    }
}

Solution 3:

It's implied for base parameterless constructors, but it is needed for defaults in the current class:

public class BaseClass {
    protected string X;

    public BaseClass() {
        this.X = "Foo";
    }
}

public class MyClass : BaseClass
{
    public MyClass() 
        // no ref to base needed
    {
        // initialise stuff
        this.X = "bar";
    }

    public MyClass(int param1, string param2)
        :this() // This is needed to hit the parameterless ..ctor
    {
         // this.X will be "bar"
    }

    public MyClass(string param1, int param2)
        // :base() // can be implied
    {
         // this.X will be "foo"
    }
}

Solution 4:

It is implied.