Tarik
Tarik

Reputation: 81711

Why base class constructor isnt called first

When using easy syntax to initialize derived class fields by directly assigning values to them, compiler emits an IL code which first initializes derived class fields and then call base .ctor. Why it doesnt call base .ctor fields and initialize the derived class fields. What if I would have fields which depend on base class's fields?

I would love to put some code sample here but I am posting this question from my mobile phone.

Upvotes: 3

Views: 683

Answers (2)

Sandeep
Sandeep

Reputation: 7334

Eric Lippert has a two part series on his blog.

http://blogs.msdn.com/b/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx

Just mentioning here for your convineance. Hope this helps.

Calling methods on derived types from constructors is dirty pool, but it is not illegal. 

And stuffing not-quite-constructed objects into global state is risky, but not illegal.

Upvotes: 2

Matthew Sanford
Matthew Sanford

Reputation: 1099

I think it is because it needs to handle the case where a virtual method or intializer is called within the constructor.

Upvotes: 4

Related Questions