Test for multiple cases in a switch, like an OR (||)
You can use fall-through: switch (pageid) { case “listing-page”: case “home-page”: alert(“hello”); break; case “details-page”: alert(“goodbye”); break; }
You can use fall-through: switch (pageid) { case “listing-page”: case “home-page”: alert(“hello”); break; case “details-page”: alert(“goodbye”); break; }
Switch cases should almost always have a default case. Reasons to use a default 1.To ‘catch’ an unexpected value switch(type) { case 1: //something case 2: //something else default: // unknown type! based on the language, // there should probably be some error-handling // here, maybe an exception } 2. To handle ‘default’ actions, where … Read more
When I looked at the solutions in the other answers I saw some things that I know are bad for performance. I was going to put them in a comment but I thought it was better to benchmark it and share the results. You can test it yourself. Below are my results (ymmv) normalized after … Read more
This is a typical scenario where subtype polymorphism helps. Do the following interface I { void do(); } class A implements I { void do() { doA() } … } class B implements I { void do() { doB() } … } class C implements I { void do() { doC() } … } Then … Read more
In a case statement, a , is the equivalent of || in an if statement. case car when ‘toyota’, ‘lexus’ # code end Some other things you can do with a Ruby case statement
Change it to this: switch (enumExample) { case VALUE_A: { //.. break; } } The clue is in the error. You don’t need to qualify case labels with the enum type, just its value.
With C# 7, which shipped with Visual Studio 2017 (Release 15.*), you are able to use Types in case statements (pattern matching): switch(shape) { case Circle c: WriteLine($”circle with radius {c.Radius}”); break; case Rectangle s when (s.Length == s.Height): WriteLine($”{s.Length} x {s.Height} square”); break; case Rectangle r: WriteLine($”{r.Length} x {r.Height} rectangle”); break; default: WriteLine(“<unknown shape>”); … Read more
(Copy/paste of an answer I provided elsewhere) Falling through switch–cases can be achieved by having no code in a case (see case 0), or using the special goto case (see case 1) or goto default (see case 2) forms: switch (/*…*/) { case 0: // shares the exact same code as case 1 case 1: … Read more
You can use have both CASE statements as follows. case text1: case text4:{ //blah break; } SEE THIS EXAMPLE:The code example calculates the number of days in a particular month: class SwitchDemo { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case … Read more
For just a few items, the difference is small. If you have many items you should definitely use a switch. If a switch contains more than five items, it’s implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where … Read more