Base constructor in C# - Which gets called first? [duplicate] Ask Question

Base constructor in C# - Which gets called first? [duplicate] Ask Question

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
    }
}

ベストアンサー1

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:

おすすめ記事