How can I shorten this method? Depending on the incoming value, it marks checkboxes.

private void CheckB(int i) { switch (i) { case 0: c1.Checked = true; return; case 1: c2.Checked = true; return; case 2: c3.Checked = true; return; case 3: c4.Checked = true; return; case 4: c5.Checked = true; return; case 5: c6.Checked = true; return; case 6: c7.Checked = true; return; case 7: c8.Checked = true; return; case 8: c9.Checked = true; return; case 9: c10.Checked = true; return; case 10: c11.Checked = true; return; case 11: c12.Checked = true; return; } 

    2 answers 2

    You can put checkboxes in an array:

     private readonly CheckBox[] checkBoxes; 

    In the constructor (after InitializeComponent(); ) we create an array:

     checkBoxes = new[] { c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12 }; 

    Then your method will look like this:

     private void CheckB(int i) { if (i >= 0 && i < checkBoxes.Length) checkBoxes[i].Checked = true; } 
    • one
      It seems to have seen that this "family" of solutions is called the tabular method - AseN
    • one
      Only the array is a bit wrong to do ... After all, before the call to InitializeComponents() there will be null everywhere. - Pavel Mayorov
    • @PavelMayorov I made an array in the method itself - Roman Kravets
    • one
      @RomanKravets is not the best solution - I bet you will need such an array in several methods :) Better make it a field as suggested - and fill in the constructor. - Pavel Mayorov
    • @PavelMayorov Thanks, I'll do it =) - Roman Kravets

    Can be done through the Dictionary. Perhaps it will be faster.

     private readonly Dictionary<int, CheckBox> checkBoxes = checkBoxes = new Dictionary<int, CheckBox>(){ {0, c1}, {1, c2}, ..., {11, c12}}; private void CheckB(int i) { CheckBox box; checkBoxes.TryGetValue(i, out box); box.Checked = true; }