Reputation: 28473
The following code gives an error: "A local or parameter named 'ac' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter".
if (action is ActionRegisterNewDevice ac)
{
state = state.ShallowCopy();
// Initialise the device to off
state.DeviceOn[ac.ObjectId] = false;
}
else if (action is ActionOnMouseDown ac)
{
state = state.ShallowCopy();
// toggle the state of the device
state.DeviceOn[ac.ObjectId] = !DeviceSelectors.Device_is_on(state, ac.ObjectId);
}
I was under the impression (obviously incorrectly) that the first conditional is a separate scope. It seems that the Pattern matching, even when false, still declares the variable ac
.
However the documentation says:
Language rules for pattern matching expressions help you avoid misusing the results of a match expression. In the example above, the variables s, c, and r are only in scope and definitely assigned when the respective pattern match expressions have true results. If you try to use either variable in another location, your code generates compiler errors.
This error can apparently only be fixed by renaming the second ac
to something else. Is this correct? Am I misunderstanding the documentation?
Upvotes: 0
Views: 268
Reputation: 37192
You should rewrite your code to use a switch statement instead to get the behaviour you want:
void Main()
{
Print("Hello world");
Print(42);
}
static void Print(object o)
{
switch (o)
{
// Note that I am reusing the variable name "value" in each case.
case string value:
Console.WriteLine("STRING: " + value);
break;
case int value:
Console.WriteLine("INT: " + value.ToString());
break;
}
}
To answer your question of why you can't do this in an if...else...
, this is called out in the documentation you link to:
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.
Upvotes: 1