How can I use wildcards in a switch statement?

I have a switch statement that uses a 3 letter string. For many cases (but not for everyone) I only want to tackle the first two letters.

For example, I want every code starting with "FF" to be processed the same way:

switch(code) { case "FF(?)": // Handle it break; default: break; } 

What can i do here? Can i use the template? Should I consider every FF code?

For obvious reasons, I do not want to have code that can grow very large:

 case "FFA": case "FFB": case "FFD": // Handle it 
+6
source share
4 answers

Make your first 2 characters on switch , not on case .

Use the default case to then return to the three letter cases. This is not the cleanest, but it will work. Sometimes if are the way to go if the switches don't cut.

 switch(code.Substring(0, 2)) { case "FF": ... default: switch(code) { case "ABC": .... } } 
+5
source

Use if then else for these comparisons. Reserve your switch case for cases that are easily identified as discrete values.

+5
source

just use the ternary operator in the switch statement

  switch (code.StartsWith("FF")? code.substring(0,2): code) { case "FF": case "FAS": case "FAY" // etc. } 

for brevity, do the following:

  switch (new[] {"FF", "GG", "HH", "JJ"}.Contains(code.substring(0,2))? code.substring(0,2): code) { case "FF": case "GG": case "HH": case "JJ": case "FAS": case "FAY" // etc. } 
+2
source

The Switch statement in C # does not support this. Instead, you will need to use if / else statements:

 if (code.StartsWith("FF")) { // Handle it } else if (code == "HFD") // etc { // Handle it } else { // default case } 
+1
source

Source: https://habr.com/ru/post/975553/


All Articles