142

Which gets called first - the base constructor or "other stuff here"?

public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message, string extrainfo) : base(message)
    {
        //other stuff here
    }
}
Mike Comstock
  • 6,640
  • 10
  • 36
  • 41

13 Answers13

173

Base class constructors get called before derived class constructors, but derived class initializers get called before base class initializers. E.g. in the following code:

public class BaseClass {

    private string sentenceOne = null;  // A

    public BaseClass() {
        sentenceOne = "The quick brown fox";  // B
    }
}

public class SubClass : BaseClass {

    private string sentenceTwo = null; // C

    public SubClass() {
        sentenceTwo = "jumps over the lazy dog"; // D
    }
}

Order of execution is: C, A, B, D.

Check out these 2 msdn articles:

Sam Meldrum
  • 13,835
  • 6
  • 33
  • 40
122

The base constructor will be called first.

try it:

public class MyBase
{
  public MyBase()
  {
    Console.WriteLine("MyBase");
  }
}

public class MyDerived : MyBase
{
  public MyDerived():base()
  {
    Console.WriteLine("MyDerived");
  }
}
craigb
  • 16,827
  • 7
  • 51
  • 62
  • 7
    You are right. But the execution starts at the derived constructor, the first thing the derived constructor does is call the base constructor(if any). So it appears as if the base constructor is being called first. – saquib adil Aug 16 '17 at 14:50
  • 1
    What if the base constructor has arguments, then would it still be automatically called? – variable Dec 20 '19 at 09:16
47

Don't try to remember it, try to explain to yourself what has to happen. Imagine that you have base class named Animal and a derived class named Dog. The derived class adds some functionality to the base class. Therefore when the constructor of the derived class is executed the base class instance must be available (so that you can add new functionality to it). That's why the constructors are executed from the base to derived but destructors are executed in the opposite way - first the derived destructors and then base destructors.

(This is simplified but it should help you to answer this question in the future without the need to actually memorizing this.)

David Pokluda
  • 10,693
  • 5
  • 28
  • 26
  • 9
    Don't remember it, understand it. Nice work. – Jerry Nixon Feb 23 '15 at 00:11
  • Except it's not always this way - the order in C++ is the opposite, and if C++ can do it, that means that the logic in this thinking is incorrect. – Steve Jun 21 '22 at 21:48
  • Which is why it's hard to remember, especially if you switch between the two on a regular basis. – Steve Jun 21 '22 at 21:49
26

Actually, the derived class constructor is executed first, but the C# compiler inserts a call to the base class constructor as first statement of the derived constructor.

So: the derived is executed first, but it "looks like" the base was executed first.

Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
  • 2
    This is one of those cases where context is important - in CLR terms, the derived constructor is executed first. In C# terms, the base constructor is executed first. There are a few oddities like this where the specs disagree; for instance, on whether structs have a parameterless constructor or not. – Jon Skeet Sep 26 '08 at 16:55
  • 7
    Actually, it looks like I spoke too fast. Now I've consulted the spec, and while it says that the constructor-initializer is executed before the constructor-body, that counts as being included in the overall constructor. So you're entirely right from both perspectives :) – Jon Skeet Sep 26 '08 at 17:02
  • What if the base constructor has arguments, then would it still be automatically called? – variable Dec 20 '19 at 09:17
  • @variable you would have to call it yourself, with `base(arguments)`. – Paolo Tedesco Dec 20 '19 at 10:40
7

As others have said, the base constructor gets called first. However, constructors are not really the first thing that happens.

Let's say you have classes like this:

class A {}

class B : A {}

class C : B {}

First, field initializers will be called in order of most-derived to least-derived classes. So first field initializers of C, then B, then A.

The constructors will then be called in the opposite order: First A's constructor, then B, then C.

Joel B Fant
  • 24,406
  • 4
  • 66
  • 67
5

I'd say base

EDIT see:

http://www.c-sharpcorner.com/UploadFile/rajeshvs/ConsNDestructorsInCS11122005010300AM/ConsNDestructorsInCS.aspx

there it says:

using System;
class Base
{

public Base()
{
    Console.WriteLine("BASE 1");
}
public Base(int x)
{
    Console.WriteLine("BASE 2");
}
}

class Derived : Base
{
public Derived():base(10)
{
    Console.WriteLine("DERIVED CLASS");
}
}

class MyClient
{
public static void Main()
{
    Derived d1 = new Derived();
}
}

This program outputs

BASE2

DERIVED CLASS

Mastermind
  • 141
  • 3
5

Base Constructor is called first. But the initializer of fields in derived class is called first.

The calling order is

  1. derived class field initializer
  2. base class field initializer
  3. base class constructor
  4. derived class constructor

(You can treat 2 and 3 as a whole to construct the base class.)

Taken from CSharp Language Speification 5.0:

10.11.3 Constructor execution

Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed. Given the example

using System;
class A
{
    public A() {
        PrintFields();
    }
    public virtual void PrintFields() {}
}
class B: A
{
    int x = 1;
    int y;
    public B() {
        y = -1;
    }
    public override void PrintFields() {
        Console.WriteLine("x = {0}, y = {1}", x, y);
    }
}

when new B() is used to create an instance of B, the following output is produced:

x = 1, y = 0

The value of x is 1 because the variable initializer is executed before the base class instance constructor is invoked. However, the value of y is 0 (the default value of an int) because the assignment to y is not executed until after the base class constructor returns. It is useful to think of instance variable initializers and constructor initializers as statements that are automatically inserted before the constructor-body. The example

using System;
using System.Collections;
class A
{
    int x = 1, y = -1, count;
    public A() {
        count = 0;
    }
    public A(int n) {
        count = n;
    }
}
class B: A
{
    double sqrt2 = Math.Sqrt(2.0);
    ArrayList items = new ArrayList(100);
    int max;
    public B(): this(100) {
        items.Add("default");
    }
    public B(int n): base(n – 1) {
        max = n;
    }
}

contains several variable initializers; it also contains constructor initializers of both forms (base and this). The example corresponds to the code shown below, where each comment indicates an automatically inserted statement (the syntax used for the automatically inserted constructor invocations isn’t valid, but merely serves to illustrate the mechanism).

using System.Collections;
class A
{
    int x, y, count;
    public A() {
        x = 1;                                // Variable initializer
        y = -1;                               // Variable initializer
        object();                         // Invoke object() constructor
        count = 0;
    }
    public A(int n) {
        x = 1;                                // Variable initializer
        y = -1;                               // Variable initializer
        object();                         // Invoke object() constructor
        count = n;
    }
}
class B: A
{
    double sqrt2;
    ArrayList items;
    int max;
    public B(): this(100) {
        B(100);                               // Invoke B(int) constructor
        items.Add("default");
    }
    public B(int n): base(n – 1) {
        sqrt2 = Math.Sqrt(2.0);           // Variable initializer
        items = new ArrayList(100);   // Variable initializer
        A(n – 1);                         // Invoke A(int) constructor
        max = n;
    }
}
zwcloud
  • 4,546
  • 3
  • 40
  • 69
2

Eric Lippert had an interesting post on the related issue of object initialization, which explains the reason for the ordering of constructors and field initializers:

Why Do Initializers Run In The Opposite Order As Constructors? Part One
Why Do Initializers Run In The Opposite Order As Constructors? Part Two

Emperor XLII
  • 13,014
  • 11
  • 65
  • 75
1

http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=777

Base Constructor gets called first.

mmcdole
  • 91,488
  • 60
  • 186
  • 222
1

The Exception Constructor will be called, then your Child class constructor will be called.

Simple OO principle

Have a look here http://www.dotnet-news.com/lien.aspx?ID=35151

CheGueVerra
  • 7,849
  • 4
  • 37
  • 49
0

The base constructor will be called first, otherwise, in cases where your "other stuff" must make use of member variables initialized by your base constructor, you'll get compile time errors because your class members will not have been initialized yet.

kafuchau
  • 5,573
  • 7
  • 33
  • 38
  • Member variables don't have the same concept of definite assignment as local variables. They have a default value. What's interesting in C# is that the variable initializers are run *before* the base constructor instead of after. (Java has the latter behaviour.) – Jon Skeet Sep 26 '08 at 16:37
0

base(?) is called before any work is done in the child constructor.

This is true, even if you leave off the :base() (in which case, the 0-parameter base constructor is called.)

It works similar to java,

public Child()
{
   super(); // this line is always the first line in a child constructor even if you don't put it there! ***
}

*** Exception: I could put in super(1,2,3) instead. But if I don't put a call to super in explicitly, super() is called.

Chris Cudmore
  • 29,793
  • 12
  • 57
  • 94
0

Constructor calls are called (fired) from the bottom up, and executed from the top down. Thus, if you had Class C which inherits from Class B which inherits from Class A, when you create an instance of class C the constructor for C is called, which in turn calls the instructor for B, which again in turn calls the constructor for A. Now the constructor for A is executed, then the constructor for B is executed, then the constructor for C is executed.