Should switch statements always contain a default clause?

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

Is there a better alternative than this to ‘switch on type’?

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

Switch statement fallthrough in C#?

(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