Win Win - 1 year ago 66
C# Question

Reducing condition within an if statement

I have an if statement to run some code when all the textboxes on a form are completed,

the way I check for all the textboxes to not be empty at the moment is below

if (txtUserId.Text != ""
&& txtFirstName.Text != ""
&& txtLastName.Text != ""
&& txtCity.Text != ""
&& txtSTate.Text != ""
&& txtCountry.Text != "")
// Some code

Is there a better way to write this?

usr usr
Answer Source

Abstract the check out into a function:

bool IsFilled(TextBox tb) { return tb.Text != ""; }

Then you can either use the old, simplified code, or this trick:

var textBoxes = new [] { txtUserId, txtFirstName, ... };
if (textBoxes.All(tb => IsFilled(tb)) { ... }

This is probably more scalable the more text-boxes you get.

You could also write textBoxes.All(IsFilled) which works due to method-group conversion to delegate. This is slightly more performant, and shorter. I find method group conversion hard to comprehend and misleading, though. Other people might ask you "what does that do?" and this indicates a code smell. I do not recommend it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download