2

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.

neizan
  • 2,291
  • 2
  • 37
  • 52

1 Answers1

3

This page has a nice explanation of what is going on. Basically, just as the error indicates, the initialized variable is available in the enclosing scope of the if and else if statements. This is similar to how out parameters work. So, yes, when using a series of if statements, you may use a variable name only once.

An alternative would be to use a switch instead of an if:

switch (item) {
    case Dog animal:
        // ...
        break;
    case Cat animal:
        // ...
        break;
    case Animal animal:
        // ...
        break;
    default:
        // Interestingly, you cannot reuse the variable name here.
        // But you could create a new scope and then reuse it.
        {
            Animal animal = ...
        }
        break;
}

The variables initialized in the switch are limited to the scope of their case. See also.

neizan
  • 2,291
  • 2
  • 37
  • 52