How to use 1 case with more than one variable?
in c #
Answer 1, authority 100%
This should work. (not sure because, unfortunately, I don’t know C # at all)
String test = "2";
switch (test)
{
case "1":
case "2":
MessageBox.Show ("The variable test is 1 or 2");
break;
default:
break;
}
I will slightly supplement the answer in connection with the new understanding of the question.
In such cases, you can use a regular IF. For example:
if (var_one == 1 & amp; & amp; var_two == 1) {// do something}
Answer 2, authority 96%
The switch multi-variable syntax is not available in C #.
As described at SO , more or less elegant way, this is to use tuples:
using System;
static class CompareTuple {
public static bool Compare & lt; T1, T2, T3 & gt; (this Tuple & lt; T1, T2, T3 & gt; value, T1 v1, T2 v2, T3 v3) {
return value.Item1.Equals (v1) & amp; & amp; value.Item2.Equals (v2) & amp; & amp; value.Item3.Equals (v3);
}
}
class Program {
static void Main (string [] args) {
var t = new Tuple & lt; int, int, bool & gt; (1, 2, false);
if (t.Compare (1, 1, false)) {
// 1st case
} else if (t.Compare (1, 2, false)) {
// 2nd case
} else {
// default
}
}
}
Answer 3, authority 96%
Option 1 – use nested cases
switch (var1)
{
case 1:
switch (var2): {
case 1:
break;
case 2:
break;
}
break;
default:
break;
}
Of course, it’s better to put nested switches in separate functions / methods.
Method 2
generate a surrogate key. For example, there are two integer keys, both in the range 1-100.
varS = var1 * 100 + var2;
switch (varS) {
case 1: // var1 = 0; var2 = 1
break;
case 204: // var1 = 2; var2 = 4;
break;
}
with string keys is the same story. We just do concatenation, preferably separating it with some unique symbol (for reliability). Since there can be two keys “test1” and “test2” versus “test” and “1test2”.