Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
732 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...