“The great power comes with a great responsibility.“
C# as a powerful language has reduced the mistakes in Switch/Case flow control by removing the implicit fall-through behavior. That says you can not pass the compilation without an explicit statement at the end of each case, either a “break”, a “return”, a “goto”, or you can also detour the control flow by “throw” an exception. AS a matter of fact, you should always throw an out-of-boundary exception at “default” case, unless you have a default value specified by the business requirement. Otherwise it’ll be very hard to find a problem at runtime such as the caller providing a parameter which is out of the enumerator’s scope and it is being tested at the “switch” in the callee module.
Try code below, it is a real scenario but simplified. The root cause in this case is a bug in C# enumeration type – you can pass compile-time inspection by providing 0 even when 0 is not defined in the enumeration.
But if we have had a “default” case in the switch structure, it will be a lot easier to identify the problem.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private enum enuPath:int
{
a =1, // enum starts from 1, 0 is not in the scope
b ,
c
}
private void button1_Click(object sender, EventArgs e)
{
NewMethod(0); // C# bug: you are able to pass in 0 which is out of the scope of enuPath
}
private static void NewMethod(enuPath EnuPath)
{
//int path = Convert.ToInt32(enuPath);
try
{
switch (EnuPath)
{
case enuPath.a:
Debug.WriteLine("In case 1\n");
break ;
case enuPath.b:
Debug.WriteLine("In case 2\n");
break;
case enuPath.c:
Debug.WriteLine("In case 3\n");
break;
//default:
// throw new Exception("suplied parameter is out of scope of enuPath");
}
Debug.WriteLine("You are not supposed reach here since 0 is not an acceptable value\n");
}
catch (Exception ex)
{
Debug.WriteLine("In exception\n");
}
}
}
}