Home > front end >  c# Assigning the same result to different objects with Switch
c# Assigning the same result to different objects with Switch

Time:11-11

I have a switch case structure like this:

var dict = new Dictionary<string, string>
{
    {"title", "title.val"},
    {"phone", "phone.val"},
    {"address", "address.val"},
    {"e_mail", "email.val"},
    {"work_phone", "workphone.val"}
};

foreach (var p in dict)
{
    string str = ___ANY_METHOD___(p.Value);
    
    if (!string.IsNullOrEmpty(str))
    {
        switch (p.Key)
        {
            case "title":
                _trp.Name = str;
                break;
            case "phone":
                _trp.Phone = str;
                break;
            case "address":
                _trp.Address = str;
                break;
            case "e_mail":
                _trp.Email = str;
                break;
            case "work_phone":
                _trp.WorkPhone = str;
                break;
        }
    }
}

Due to the difference in the incoming values, there is no error in the switch case structure and the program runs smoothly as it is. But as it stands, the code snippet looks pretty ugly. Is there a better way to assign the same value to prs.Name, prs.Phone, prs.Address, prs.Email, prs.WorkPhone objects in the switch case structure?

CodePudding user response:

Why don't you just set the properties and drop the switch?

if (!string.IsNullOrEmpty(dict["title"])
    _trp.Name = ___ANY_METHOD___(dict["title"])[0].ToString();
if (!string.IsNullOrEmpty(dict["phone"])
    _trp.Phone = ___ANY_METHOD___(dict["phone"])[0].ToString();
if (!string.IsNullOrEmpty(dict["address"])
    _trp.Address = ___ANY_METHOD___(dict["address"])[0].ToString();
if (!string.IsNullOrEmpty(dict["e_mail"])
    _trp.Email = ___ANY_METHOD___(dict["e_mail"])[0].ToString();
if (!string.IsNullOrEmpty(dict["work_phone"])
    _trp.WorkPhone = ___ANY_METHOD___(dict["work_phone"])[0].ToString();

It requires that ANY METHOD has no side-effects.

CodePudding user response:

Both Are Correct

case "title" or "phone" or "address" or "e_mail" or "work_phone":

case "title","phone","address","e_mail","work_phone":

Your Answer is :

switch (p.Key)
{
    case "title" or "phone" or "address" or "e_mail" or "work_phone":
        prs.Name = prs.Phone =  prs.Address = prs.Email = prs.WorkPhone = _obj[0].ToString();
        break;
.
.
.
//if you have other cases

}
  • Related