C#: Better way to refactor method to display appropriate groupbox and hide others? – Education Career Blog

Is there a better way to refactor the following method which’s purpose is to make sure the appropriate groupbox is the one displayed apart from the others as if they’re cycled through a list? Is it possible to refactor this all into one solo if statement + “with no elses keywords”?

    // DisplayGroupBox(grpSounds);
    void DisplayGroupBox(GroupBox GroupBoxControls)
        grpSounds.Visible = false;
        grpAlerts.Visible = false;
        grpFilters.Visible = false;

        GroupBox.Visible = true;

Edited: I meant on ways to refactor in one statement to display appropriate groupbox with no else statements. Perhaps a way using the &&, ||, and such operators.


I’d probably just leave the method as is. You can squeeze all of those operations into one line, but the intent of the method won’t be as clear. I think it is fine the way it is, no amount of refactoring can really make it simpler.


If you have your group boxes in a collection (i.e. just add grpSounds, grpAlerts, grpFilters to a list) you could do:

void DisplayGroupBox(GroupBox groupControlYouWantToDisplay)
    foreach(var box in listControls.Where(gb => gb != groupControlYouWantToDisplay)
       box.Visible = false;
    groupControlYouWantToDisplay.Visible = true;

Leave a Comment