Home > Back-end >  any way to use variables in c# switch case?
any way to use variables in c# switch case?

Time:07-17

I know that case cannot work with non-constant values, but what should I do if its impossible to make a constant? thats my case: we have three variables, need to find that, one that will correspond to the value of the switch condition, but how to do this if the case is not able to work with non-constants? are there any workarounds?

float value = 4;
float number1 = 3, number2 = 6, number3 = 4;

switch (value)
{
    case number1:
        {
             break;
        }
    case number2:
        {
             break;
        }
    case number3:
        {
             break;
        }
}

here is the oversimplified example, and yes, you can easily do this using if/else if, but what if the number of values will be 100? what to do in that case?

CodePudding user response:

One approach is to use an inverted Dictionary, where the key is the value and the value the key. Something like this:

var d = new Dictionary<int, int>();   

d.Add(3, 1);  
d.Add(6, 2);  
d.Add(4, 3);  

int keyPtr = d[value];  

switch (keyPtr):  
{  
    case 1:  
        //do something. 
        break;  
    case 2:  
        //do something else. 
        break;  
    case 3:  
        //do something different. 
        break;  
}  

Obviously this is simplified, and I have used int not float, but the same applies to any type. Using this technique, your n variables, become the first n items in the Dictionary. In practice at the very least, you should check if your given value exists as a key in the Dictionary. It should help you in the right direction.

CodePudding user response:

If you simply want to check whether your value variable equals to at least one of the variables number1, number2, number3, you could create an array of those numbers, say numbers[] and then create a method such as:

private bool checkValue(float value, float[] numbers) {

    foreach (float num in numbers) {
        if (num == value) return true;
    }
    return false;

}

This solution fits any number of elements in your numbers array. If you want you can also use a List<float> instead of an array, so you could dynamically add more and more elements (Without a fixed size).

  • Related