Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing field by default value is redundant

Tags:

c#

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?

like image 321
Lea Cohen Avatar asked Nov 06 '08 11:11

Lea Cohen


People also ask

What is redundant initializer?

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.

What is field initialization?

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; } }

Do fields have to be initialized?

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.


2 Answers

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”.

like image 168
tamberg Avatar answered Sep 23 '22 20:09

tamberg


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.

like image 27
Jon Skeet Avatar answered Sep 24 '22 20:09

Jon Skeet