❔ 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
correct
field initializers run before constructor, as you might need to interact with those fields/values in the ctor
Thank you very much for the answer! This is really important to me.
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-conventionsYou can
/close
the thread if you don't have any further questions.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.