I am using the C# 7.0 syntax to initialize a variable when checking the type using the is
operator. I want to use the same variable name, say "animal", for all scenarios, like this:
// Yes, polymorphism may be better. This is just an illustration.
if (item is Dog animal) { // ... }
else if (item is Cat animal) { // ... }
else if (item is Animal animal) { // ... }
else { // ... }
However, I get an error that says the variable name is used in an enclosing scope. Is there a way to get around this? I'd really rather not have to use different variable names for each else if
statement.