Reputation: 8200
Can I really and truly trust .NET to initialize fields (like ints, structs and the like)? And what if I still want to initialize those fields - what could be the repercussions?
Upvotes: 13
Views: 6108
Reputation: 2017
The C# specification states on p.305 (17.4.4)
The initial value of a field, whether it be a static field or an instance field, is the default value (§12.2) of the field’s type. It is not possible to observe the value of a field before this default initialization has occurred, and a field is thus never “uninitialized”.
Upvotes: 18
Reputation: 1503280
Yes, you can really trust .NET to initialize fields to their default values. There are basically no repercussions for doing it explicitly. (One small caveat here: if you initialize static fields explicitly, then anyone running the type initializer a second time via reflection will end up re-initializing those fields. This is a real corner case though!)
Do whatever promotes the most readability in your particular codebase.
Upvotes: 12