I'm trying to get the value alpha and beta displayed OUTSIDE a switch, but the compiler throws Compiler Warning (level 2) CS0162
(Unreachable code detected).
Any help is greatly appreciated.
private void TestButton_Click(object sender, EventArgs e)
{
string alpha;
byte beta = 0;
alpha = comboBoxAlpha.Text;
switch (alpha)
{
case "charlie":
beta = 1;
return;
default:
beta = 0;
return;
}
if (beta == 0)
{
label1.Text = alpha;
}
else label1.Text = beta;
}
There's no need in that complex code. As fas as I can see, you want "1" on "cahalie" and comboBoxAlpha.Text otherwise.
private void TestButton_Click(object sender, EventArgs e) {
if (comboBoxAlpha.Text == "charlie")
label1.Text = "1";
}
Or even
private void TestButton_Click(object sender, EventArgs e) =>
label1.Text = comboBoxAlpha.Text == "charlie" ? "1" : comboBoxAlpha.Text;
The problem in your code is in return instead of break: returns return from the method, when break
just breaks the switch:
private void TestButton_Click(object sender, EventArgs e)
{
string alpha;
byte beta = 0;
alpha = comboBoxAlpha.Text;
switch (alpha)
{
case "charlie":
beta = 1;
break; // Just break (jump out of) switch
default:
beta = 0;
break; // Just break (jump out of) switch
}
if (beta == 0)
{
label1.Text = alpha;
}
else label1.Text = beta;
}