There are lots of ways to refactor this sort of code to give something more succinct. It really does become a matter of experience and preference to choose the method that is appropriate for each case.
To that end, I've listed below several options that I find serve me well:
Binding
Binding particularly within WPF gives a very powerful way of easily updating form objects. In your Xaml you apply a datacontext (generally for the form/window) and bound property for each object which then allows you to then update properties in your c# code and have them automatically reflected in the form objects.
One big advantage of this is getting all that tedious object.Text = "xyz"
code out of the way.
In your given example, you could introduce a boolean property TextBoxesEnabled
which is bound to the enabled property of your text boxes, and reflects whether a == b.
Domain objects
This follows on from the binding approach—in your example above it looks like all your properties are dependant of only two external pieces of data ("a" and "b"). In this situation your are often limited to doing something just like you have, where you need to set your UI properties within lots of procedural code.
However, more often you can introduce expressive domain objects that have properties that map directly to UI properties. For example, perhaps you have a User
object, with a Name
property, and then a user window, with a name textbox.
Now your domain object will be provided by calls into your service layer and data access infrastructure, and due to binding automatically displayed in your UI.
Code refactoring
Even where you are needing to set lots of properties directly without the ability to use more expressive objects and binding, there will often be some simple refactorings that can help.
In the code example you gave, two easy refactorings leap out to me:
a == b
is a Boolean evaluation so you could have something like:
bool enableTextBoxes = a == b;
TextBox1.Enabled = enableTextBoxes;
TextBox2.Enabled = enableTextBoxes;
// etc...
You are setting the text to the same thing in the branches of the if
, so take that out of the if
and just have it once (though I'm guessing this is just because you were giving trivial example code).
You can loop over collections of controls, so if you need to set large numbers of control values to the same thing you can just do iterate over them and assign to each.