rjmurillo / EffectiveCSharp.Analyzers

Many of the recommendations in the book Effective C#: 50 Specific Ways to Improve Your C# can be validated by Roslyn-based analyzers and code fixes.
MIT License
2 stars 1 forks source link

Item 12: Prefer Member Initializers to Assignment Statements #36

Closed rjmurillo closed 1 month ago

rjmurillo commented 2 months ago

Related: https://github.com/BillWagner/EffectiveCSharpAnalyzers/issues/12, #34

Should be easy: Any field init in a ctor that doesn't use an argument should be a candidate.

Summary

This feature request aims to enhance the code analyzer library by adding a rule that enforces the use of member initializers over assignment statements in constructors. This will help developers maintain consistent initialization logic and reduce code duplication.

Goals

Explanation

Problem Statement

Using member initializers to initialize variables directly where they are declared ensures that the variables are consistently initialized regardless of which constructor is called. This approach simplifies code maintenance and reduces the risk of uninitialized variables. Member initializers should be preferred over assigning values within constructors, especially when the initialization logic is the same across all constructors.

Member initializers help maintain consistency and reduce code duplication:

Using member initializers also has some caveats: