Search code examples
c#performancereadability

C# performance and readability with buttons enabling/disabling


I've often found myself in front of that kind of code :

if(Something > 0)
{
    btnOne.Enabled = true;
    btnTwo.Enabled = true;
    btnThree.Enabled = false:
}
else
{
    btnOne.Enabled = false;
    btnTwo.Enabled = false;
    btnThree.Enabled = true:
}

And I've always wondered if it was better to let it like that, or put it like this :

bool ButtonEnabled = (Something > 0);

btnOne.Enabled = ButtonEnabled;
btnTwo.Enabled = ButtonEnabled;
btnThree.Enabled = !ButtonEnabled;

Realizing the question is a bit argumentative, let's put aside the "readability" factor and concentrate on the performance factor... What would be best ? One more assignation or a condition ?

Thanks in advance for your advices (or a even better way to write it) !

Edit : Corrected an error in my second snippet. Edit : The two initial examples weren't equivalent...


Solution

  • That depends on the properties being called. As you know, a property can do any amount if things. In Windows Forms or WPF, I wouldn't worry about it. I'd argue for the latter style for correctness and readability. If you set all necessary variables every time, there is less chance of missing something and leaving one button in an invalid state.

    I'd do something like

    bool ButtonEnabled = (Something > 0);
    btnOne.Enabled = ButtonEnabled;
    btnTwo.Enabled = ButtonEnabled;
    btnThree.Enabled = !ButtonEnabled;
    btnFour.Enabled = !ButtonEnabled;