I tried comparing an integer variable, myVar, with an integer value stored in a dictionary, myDict, using a switch statement.
I get an error
An expression of type 'int' cannot be handled by a pattern of type 'myDict[]'
This is my code:
Dictionary<string, int> myDict = new Dictionary<string, int>()
{
["Mary"] = 1,
["John"] = 2
};
void MyMethod()
{
int myVar = 1;
switch (myVar)
{
case myDict["Mary"]: // Error here
Console.WriteLine("Okay");
break;
}
}
But when I use an if statement, it works just fine:
Dictionary<string, int> myDict = new Dictionary<string, int>()
{
["Mary"] = 1,
["John"] = 2
};
void MyMethod()
{
int myVar = 1;
if (myVar == myDict["Mary"]) // Works just fine
{
Console.WriteLine("Okay");
}
}
Am I doing something wrong?
The expressions inside of case statements must be constant. C# dictionaries and their entries are not constant, and therefore will not work inside of case statements. This, for instance, will work:
// Test is constant
const int test = 1;
int myVar = 1;
switch (myVar)
{
case (test):
Console.WriteLine("Okay");
break;
}
This will not:
// Test is not constant
int test = 1;
int myVar = 1;
switch (myVar)
{
case (test): // Error here
Console.WriteLine("Okay");
break;
}
This occurs because switch statements are converted into hash tables at compile time - that's why they're considered more efficient solutions when conditions permit them. If you need to compare against dynamic values like those in your dictionary, you'd be best off using if statements. You can read more about switch statements here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With