This rule raises an issue when a local variable is declared without initialization and the immediately following statement unconditionally assigns a value to it.
Why is this an issue?
Separating variable declarations from their first assignments reduces code readability and makes it harder to understand the variable’s purpose and initial value at a glance.
When a declaration is immediately followed by an unconditional assignment to that variable, the two statements should be combined. This practice makes the code more concise and easier to follow.
Combining declaration and initialization also helps prevent bugs from accidentally using uninitialized variables and makes the variable’s scope and lifetime clearer.
This rule only reports a declaration when the assignment is the very next statement. If other statements appear in between, or the value depends on
conditional logic such as an if, a loop, a switch or a try block, no issue is raised, because moving the
declaration could change the meaning of the code.
No issue is raised either when the assigned expression refers to the variable being declared, as in a recursive lambda or a self-unsubscribing event handler. Joining those statements would not compile.
What is the potential impact?
This is primarily a code readability issue. While it doesn’t directly cause bugs, it can make code harder to understand and maintain, potentially leading to mistakes when modifying the code later.
How to fix it
Merge the declaration and the assignment into a single statement. You can use either an explicit type or the var keyword based on your
coding style preferences.
Code examples
Noncompliant code example
int Bar()
{
int myInt; // Noncompliant
myInt = 3;
return myInt - 1;
}
Compliant solution
int Bar()
{
var myInt = 3;
return myInt - 1;
}
Exceptions
No issue is raised when a statement separates the declaration from the assignment, or when the assigned value depends on conditional logic.
int Bar(bool condition)
{
int myInt; // Compliant - a statement separates the declaration from the assignment
DoSomething();
myInt = 3;
int other; // Compliant - the value is determined by conditional logic
if (condition)
{
other = 1;
}
else
{
other = 2;
}
return myInt + other;
}
Resources
Documentation
- Microsoft Learn - C# Coding Conventions - Implicitly typed local variables