Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize virtual automatic property?

Tags:

c#

c#-3.0

Is there a way to initialize virtual automatic property without using a constructor ? or should i just make a private field ?

like image 477
Hannoun Yassir Avatar asked Dec 19 '25 00:12

Hannoun Yassir


2 Answers

Virtual or not, you need a constructor. Or it will have the default-value for it's type.


Because it is not good to call a virtual member in constructor

Correct, you will have to step carefully. The normal rules do apply. To be safe you would design your property so that it doesn't need initialization or only initialize it in derived constructors where either the class or the property is sealed.

like image 154
Henk Holterman Avatar answered Dec 21 '25 14:12

Henk Holterman


Note that there will be plenty of cases where automatic properties makes little or no sense.

In the case of a virtual automatic property, I would say that the initialization part makes this a problem, and would remove the "automatic" part and create a backing field.

Of course, since base constructors are called before descendant constructors, if a base constructor initializes the property to the wrong value, a descendant constructor has a chance to rectify that before construction of the object is final.

like image 38
Lasse V. Karlsen Avatar answered Dec 21 '25 15:12

Lasse V. Karlsen



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!