Maybe this question has been answered before, but the word if occurs so often it’s hard to find it.
The example doesn’t make sense (the expression is always true), but it illustrates my question.
Why is this code valid:
StringBuilder sb;
if ((sb = new StringBuilder("test")) != null) {
Console.WriteLine(sb);
}
But this code isn’t:
if ((StringBuilder sb = new StringBuilder("test")) != null) {
Console.WriteLine(sb);
}
I found a similar question regarding a while statement. The accepted answer there says that in a while statement, it would mean the variable would be defined in each loop. But for my if statement example, that isn’t the case.
So what’s the reason we are not allowed to do this?
This is because section 8.5.1 of the C# language spec. states:
This basically means that, when you do:
You’re, in effect, doing the exact same thing as:
As such, there is no longer a return value for your check against
!= null, as the assignment isn’t a single expression, but rather a statement, which is a local-variable-declarator comprised of an identifier followed by an expression.The language specification gives this example, stating that this:
Is exactly equivalent to: