Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why base class constructor isnt called first

Tags:

c#

.net

clr

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.

like image 512
Tarik Avatar asked May 26 '26 14:05

Tarik


2 Answers

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

like image 141
Matthew Sanford Avatar answered May 30 '26 05:05

Matthew Sanford


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.

like image 41
Sandeep Avatar answered May 30 '26 05:05

Sandeep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!