I have a 'search page' where it is required that at least one textbox has some input. The following method verifies this like so:
if (!String.IsNullOrEmpty(txtNome.Text))
{
return true;
}
if (!String.IsNullOrEmpty(txtEndereco.Text))
{
return true;
}
if (!String.IsNullOrEmpty(txtCidade.Text))
{
return true;
}
if (!String.IsNullOrEmpty(txtCEP.Text))
{
return true;
}
return false;
There hasn't been any problems with the results from this method. My question is related to performance: Is there a better way to make this check? One possible alternative I've thought of:
string X = String.Concat(txtNome.Text,...,txtCEP.Text)
if(!String.IsNullOrEmpty(X))
{
return true;
}
I think that using the if-return pattern is better when the first field isn't empty, but for other use-cases, using String.Concat
is better.
Could someone let me know which way is better and why? Is there another, even better way?
If all the controls are of the same type, you could put all the controls you want to check in an array then use Linq's Any
extension method:
return new[] { txtNome, txtEndereco, txtCidade, txtCEP }
.Any(x => !String.IsNullOrEmpty(x.Text));
Or alternatively, if not all of the controls are of the same type, create an array of strings:
return new[] { txtNome.Text, txtEndereco.Text, txtCidade.Text, txtCEP.Text }
.Any(x => !String.IsNullOrEmpty(x));
The performance difference between this and a plain old if
-else
-block will be negligible.