Why is the “is”-operator in an if a longer scope then the if?

浪子不回头ぞ 提交于 2021-02-10 08:15:57

问题


So my question is:

Why (and maybe how to avoid it) has the Is-operator in C# a longer lifetime as used in an if?

Example:

Animal a = new Cat();
if (a is Cat c)
{
    Console.WriteLine(c); // Works
}

Console.WriteLine(c); // Works too

// Leads to an error because c is allready declared
if (a is Cat c)
{
    ....
}

What I would expect is, that because I declared the variable c within the if-condition, that it will be scoped to that if-condition, what is not true.

Edit: I understand the bracket argument (a scope starts with the bracked and ends with it). BUT

Why is a for loop that different then?

for (int i = 0; i<3; i++)
{
....
}

Console.WriteLine(i) // error

回答1:


You expectations may not always match the language specifications all the time. I think you may already know then name but what you are using is called Pattern Matching. Here are the rules for the scope of Pattern Matching taken from MSDN (I am copy an pasting the related section:

public static double ComputeAreaModernIs(object shape)
{
   if (shape is Square s)
       return s.Side * s.Side;
   else if (shape is Circle c)
       return c.Radius * c.Radius * Math.PI;
   else if (shape is Rectangle r)
       return r.Height * r.Length;
    // elided
    throw new ArgumentException(
        message: "shape is not a recognized shape",
        paramName: nameof(shape));
}

The variable c is in scope only in the else branch of the first if statement. The variable s is in scope in the method ComputeAreaModernIs. That's because each branch of an if statement establishes a separate scope for variables. However, the if statement itself doesn't. That means variables declared in the if statement are in the same scope as the if statement (the method in this case.) This behavior isn't specific to pattern matching, but is the defined behavior for variable scopes and if and else statements.

Simply put your scope will start with { and end with}



来源:https://stackoverflow.com/questions/62978951/why-is-the-is-operator-in-an-if-a-longer-scope-then-the-if

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!