webdreamer webdreamer - 1 year ago 210
C# Question

C# constructor execution order

In C#, when you do

Class(Type param1, Type param2):base(param1)

is the constructor of the class executed first, and then the superclass constructor is called or does it call the base constructor first?

Answer Source

The order is:

  • Member variables are initialized to default values for all classes in the hierarchy

Then starting with the most derived class:

  • Variable initializers are executed for the most-derived type
  • Constructor chaining works out which base class constructor is going to be called
  • The base class is initialized (recurse all of this :)
  • The constructor bodies in the chain in this class are executed (note that there can be more than one if they're chained with Foo() : this(...) etc

Note that in Java, the base class is initialized before variable initializers are run. If you ever port any code, this is an important difference to know about :)

I have a page with more details if you're interested.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download