dimanche 29 avril 2018

Rewriting multiple if statements

I am looking for best practice to write multiple if statements and making code more reusable. these are my if statements that i wuld like to change

    public DataSet getOrganizationDataSet(string organizationType, string 
    name, string state, string city, string county, string zip)
    {
        string search = "";

        if (organizationType != "")
        {
            search = search + "&type=" + organizationType;
        }
        if (name != "")
        {
            search += "&name=" + name;
        }
        if (city != "")
        {
            search = search + "&town=" + city;
        }
        if (zip != "")
        {
            search = search + "&zip=" + zip;
        }
        if (county != "")
        {
            search = search + "&county=" + county;
        }
        if (state != "")
        {
            search = search + "&state=" + state;
        }
}

i am thinking about writing code like this to make it more readable:

 public DataSet getOrgDataSet(string type, string name, string state, 
 string city, string county, string zip)
    {
        string search = "";

        if ((type ?? state ?? name ?? city ?? county ?? zip) != "") {

            search += "&type=" + type;
            search += "&name=" + name;
            search += "&town=" + city;
            search += "&county=" + county;
            search += "&zip=" + zip;
            search +=  "&state=" + state;

     }

I would like to know your opinion on this and best practices. Thanks in advance, and sorry for novice question, i am still learning c#

Aucun commentaire:

Enregistrer un commentaire