Pattern match variable scope

前端 未结 2 701
悲&欢浪女
悲&欢浪女 2021-01-11 10:41

In the Roslyn Pattern Matching spec it states that:

The scope of a pattern variable is as follows:

If the pattern appears in the condition

2条回答
  •  广开言路
    2021-01-11 11:12

    From that same documentation:

    the variables introduced by a pattern – are similar to the out variables described earlier

    So actually this code:

    if (!(o is int i)) return; // type pattern "int i"
    

    Is more or less equal to:

    int i;
    if (!(SomeParsingOn(o, out i))) return; // type pattern "int i"
    

    That means that i is declared on the same level as the if, which means it is in scope not only for the if, but also for following statements. That this is true can be seens when you copy the if:

    if (!(o is int i)) return; // type pattern "int i"
    if (!(o is int i)) return; // type pattern "int i"
    

    Gives error CS0128: A local variable named 'i' is already defined in this scope.

提交回复
热议问题