Mohamed Ahmed Mohamed Ahmed - 5 months ago 14
C# Question

Checking for equality to the same value for more than one variable C#

Is there a shorthand version of this comparison statement:

if (txtId.Text != string.Empty && txtName.Text != string.Empty && txtBOD.Text != string.Empty && txtPhone.Text != string.Empty)
{//do something }

Is there something like: if all these textboxs values != string.Empty, then do something


You could put the textboxes in an array and use linq like that:

TextBox[] boxes = new [] {txtId, txtName, txtBOD, txtPhone};
if (boxes.All(b => !string.IsNullOrEmpty(b.Text)))
    // do something

You should store the array in a member variable of your window so you don't have to create it again for every check.

Or (as Habib pointed out) if all those textboxes are in one container control and they are the only textboxes on that control you could use this:

if (containingControl.Controls.OfType<TextBox>().All(b => !string.IsNullOrEmpty(b.Text)))
    // do something

OfType<>() returns a enumeration of all controls in the containingControl's control collection that are of type TextBox and you can then simply iterate through this sequence with All.

Note (as others pointed out) that it's a better practice to use string.IsNullOrEmpty() than comparing against string.Empty (since a null check is already included, though that should not matter at a textbox).