JNF JNF - 10 days ago 5
C# Question

When Do C# Auto-Properties Initialize?

On a webforms

.aspx
page system, the master page has a few properties auto initialized, as such

public bool MyProp => bool.Parse(Service.Settings["YorN"]);


Profiling page load, I see that between the
PreRender
event, and the initialization of one of the properties there is a large gap.

Where can I look to figure out the delay? What runs between the two?

Answer

That is not an auto property. That's an expression bodied member.

Your implementation of MyProp computes bool.Parse(Service.Settings["YorN"]); every time the property getter is called. So in your case, that code is run whenever MyProp is called, and it's run each time it's called.

If you used an auto property, which would be

public bool MyProp {get;} = bool.Parse(Service.Settings["YorN"]);

Then it would be run after the instance is created, and just before the constructor is called (when other field initializers run). Note that, as this code runs in a field initializer, it cannot use the implicit reference (this) so if Service is an instance variable, this won't compile.

Comments