Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to compare an int variable with an int value stored in a dictionary

Tags:

c#

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?

like image 314
Janna Ukoko Avatar asked Oct 24 '25 01:10

Janna Ukoko


1 Answers

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.

like image 56
AbeMonk Avatar answered Oct 26 '25 14:10

AbeMonk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!