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
Detect instances where variables are assigned in constructors.
Suggest refactoring to use member initializers for consistent initialization.
Improve code readability and maintainability.
Reduce the risk of uninitialized variables.
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:
Consistency: Ensures that member variables are always initialized, regardless of which constructor is used.
Simplicity: Reduces the need to repeat initialization logic in every constructor.
Readability: Makes it clear at the declaration point what the initial value of the variable is.
Using member initializers also has some caveats:
Avoid Redundant Initialization: Do not use member initializers if you are setting the variable to its default value (e.g., 0, null).
Avoid Multiple Initializations: Be careful not to initialize the same variable in both the member initializer and the constructor.
Related: https://github.com/BillWagner/EffectiveCSharpAnalyzers/issues/12, #34
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: