Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

best way to write code of bool that check 6 functions?

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading