I have this code:
bool validInput = !string.IsNullOrWhiteSpace(reg_name_tbx.Text)
&& !string.IsNullOrWhiteSpace(reg_adr_tbx.Text)
&& !string.IsNullOrWhiteSpace(reg_phn_tbx.Text)
&& !string.IsNullOrWhiteSpace(reg_pwr_tbx.Text)
&& !string.IsNullOrWhiteSpace(reg_email_tbx.Text)
&& !string.IsNullOrWhiteSpace(reg_type_cbx.Text);
Is there a better way to write this?
It is checking that all text boxes have valid input from the user..
>Solution :
As mentioned in the comments, you cannot make your code any more performant than it already is. There is no overload for string.IsNullOrWhiteSpace that takes multiple parameters and you will have to check each string individually.
That said, if you want to make the code more terse, you can encapsulate the check in a method that takes an array of strings:
public bool DoAllStringsHaveContent(params string[] input)
{
foreach (var item in input)
{
if (string.IsNullOrWhiteSpace(item))
return false;
}
return true;
}
You can then call it like so:
bool validInput = DoAllStringsHaveContent(reg_name_tbx.Text,
reg_adr_tbx.Text, reg_phn_tbx.Text, reg_pwr_tbx.Text,
reg_email_tbx.Text, reg_type_cbx.Text);
And for completeness’ sake, if you want to do this in a "one-liner" without a reusable method, you can use LINQ:
bool validInput = new string[]
{
reg_name_tbx.Text, reg_adr_tbx.Text, reg_phn_tbx.Text,
reg_pwr_tbx.Text, reg_email_tbx.Text, reg_type_cbx.Text
}.All(x => !string.IsNullOrWhiteSpace(x);