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?
The variable's value is assigned but never used, making it a dead store. This variable's initial value is not used. After initialization, the variable is either assigned another value or goes out of scope.
A field initializer allows you to initialize a field inline, instead of inside of a constructor. For example, instead of doing: class MyClass() { int a; int b; public MyClass() { a = 5; b = 3; } }
For more information, see Constants. A field can be declared required. A required field must be initialized by the constructor, or by an object initializers when an object is created.
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”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With