-3

How can i rewrite this code using switch statements for message box to make code smaller and faster?

     //  panel1.Visible = checkBoxCCF.Checked;
        panel2.Visible = checkBoxReliabilty.Checked;
        panel3.Visible = checkBoxRisk.Checked;
        panel4.Visible = checkBoxSaftey.Checked;
        panel5.Visible = checkBoxSensitivity.Checked;
        panel6.Visible = checkBoxThroughput.Checked;
        panel7.Visible = checkBoxUncertainity.Checked;


        if (checkBoxCCF.Checked)
        {
            DialogResult result = MessageBox.Show("Do you  do want to know           more about " + checkBoxCCF.Text, "Warning",
            MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                //code for yes
            }
            else if (result == DialogResult.No)
            {
                panel1.Visible = checkBoxCCF.Checked;
            }
            else if (result == DialogResult.Cancel)
            {
                //code for Cancel
            }
  • 3
    `switch` is *not* faster than consecutive `if`/`else` branches. – Thorsten Dittmar May 28 '14 at 11:11
  • it won't be faster and in this case also not smaller... – Smartis has left SO again May 28 '14 at 11:11
  • Faster? Not in this case. More info: [here](http://stackoverflow.com/questions/395618/is-there-any-significant-difference-between-using-if-else-and-switch-case-in-c) and [here](http://stackoverflow.com/questions/767821/is-else-if-faster-than-switch-case) – Loetn May 28 '14 at 11:13
  • @ThorstenDittmar, `switch` can be faster if you have a very large set of densely packed elements. Under the covers it can make a [jump/branch table](https://en.wikipedia.org/wiki/Branch_table) which reduces the tests from O(N) to O(logN). For such a small number of targets it won't make a difference. More information is available on the [MSIL switch](http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.switch(v=vs.110).aspx) opcode MSDN page. – Drew Noakes May 28 '14 at 11:13
  • @DrewNoakes After the edit period I noticed I should have written is *not generally* faster... – Thorsten Dittmar May 28 '14 at 11:21

1 Answers1

2

You can switch on enums:

switch (result)
{
    case DialogResult.Yes:
        // Code for yes...
        break;
    case DialogResult.No:
        // Code for no...
        break;
    case DialogResult.Cancel:
        // Code for cancel...
        break;
}

However this is unlikely to be any faster. I would favour whichever approach looks cleanest in a given example.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742