C
C#2y ago
_skimi

❔ Field initialization

Good day everyone. I wanted to know what is the difference between field initialization in the class constructor and outside the constructor. I needed to know which fields would be initialized first in the constructor or after the constructor. As a result, I had to look at the IL code. It turns out that the fields that are located behind the constructor are initialized first than the fields located in the constructor?
5 Replies
Pobiega
Pobiega2y ago
correct field initializers run before constructor, as you might need to interact with those fields/values in the ctor
_skimi
_skimiOP2y ago
Thank you very much for the answer! This is really important to me.
Denis
Denis2y ago
another note: if your field will be set only once, e.g., from the constructor, mark it as readonly. See here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly#readonly-field-example And one final nitpick, the naming convention for fields is _myFieldName. See more here: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions
Pobiega
Pobiega2y ago
You can /close the thread if you don't have any further questions.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server