lex82
lex82

Reputation: 11297

Why is Resharper's default inspection severity for "redundant field initializer" set to "warning"

Resharper often complains that I explicitly initialize fields in my classes although it is redundant because without initialization they would have the same (default) value. However, I often prefer the explicit initialization because IMHO the code becomes a bit clearer and I have to think less when reading code.

However, when I just wanted to switch off this inspection, I noticed the default severity is set to "warning". Until now I always thought this was just a hint for on opportunity to remove some characters of code but now I am wondering if there is really a risk involved when using redundant initializers.

Am I missing something? What kinds of bugs can occur with redundant initializers?

Upvotes: 1

Views: 738

Answers (1)

Anton Gogolev
Anton Gogolev

Reputation: 115691

Microsoft explains why redundant field initialization is, well, redundant, this way:

In most cases, initializing a field to its default value in a constructor is redundant, which degrades performance and adds to maintenance costs.

Performance costs are negligible, if at all present (thanks @lex82 for the find):

We eliminated rule CA1805 because the cases where it fired weren't really interesting or helpful. In a Release build the user's code that is initializing a variable to the type's default value gets optimized away by the compiler. In Debug builds most of the warnings are against generated code which the user can't really do anything about.

Yet mental overhead is something to be considered. When one is accustomed to the default behavior of fields being initialized to default values, seeing redundant initialization is an immediate "WAT?". What is this here for? Are we working around some undocumented behavior or a compiler/runtime/JIT bug? Or is binary serialization messing with fields somehow? Or something else entirely?

Upvotes: 5

Related Questions