Calling a parent constructor after the child's in C#

In UnityScript, you can call a parent’s constructor whenever you want inside a child constructor with super().
It let’s you process stuff in the child constructor before you call the parent constructor.

(How) can I do that in C# (and Boo) ?

The default behaviour calls the parent constructor before anything happens in the child constructor.

Thanks in advance.

The short answer is that you can’t. C# assumes that a base class’s constructor is absolutely necessary and must always be called before anything else.

A possible workaround, however, is to specify the argument to the base class constructor via a static method. That static method will then be called on grabbing arguments to the base class instructor so will happen first.

As an example:

public class Baser
{

    public Baser(int a)
    {
        Debug.Log(a);
    }
}

public class Deriver : Baser {

    public Deriver(int a, int b) : base(Processor(a, b))  {
    }

    public static int Processor(int a, int b) {
        Debug.Log(b);
        return a;
    }
}

Here, calling new Deriver(10, 20); will result in the derived class calling it’s Log function before the one in the base classes constructor, and so the output would be

20
10

In C# base constructors are always called before any child constructor. CIL, the language C#, boo and UnityScript are based on, seems to support calling a chils constructor before the base constructor. However i don’t see any good reason for doing that. You might want to overthink your class design. The base class shouldn’t be dependend on the derived class.

Here’s a way that works, but i wouldn’t recommend it:

public class BaseClass
{
    public BaseClass()
    {
        Debug.Log("BaseClass");
        Init();
    }
    public virtual void Init()
    {
        Debug.Log("Base Init");
    }
}


public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
        Debug.Log("DerivedClass");
    }
    public override void Init()
    {
        Debug.Log("Derived Init");
        base.Init();
    }
}

This will cause the following output:

BaseClass
DerivedClass
Derived Init
Base Init

This code above gave me the below when doing ‘new DerivedClass();’. Funny :slight_smile: .net 4.5

BaseClass
Derived Init
Base Init
DerivedClass