Home > Net >  C# simplify switch statement
C# simplify switch statement

Time:12-03

Can I somehow simplify this switch statement as both cases do same thing just with another function parameter?

switch (data.Subscriber.Protocol)
{
    case "email json":
        builder.Attachments.Add("Očitanje.json", CraftAttachment(data));
        break;
    case "email text":
        builder.Attachments.Add("Očitanje.txt", CraftAttachment(data));
        break;
    default:
        break;
}

CodePudding user response:

How about something like this:

string attachmentName = data.Subscriber.Protocol switch
{
    "email json" => "Očitanje.json",
    "email text" => "Očitanje.txt",
    _ => null
};

if (attachmentName is not null)
{
    builder.Attachments.Add(attachmentName, CraftAttachment(data));
}

Switch expression | C# reference

CodePudding user response:

//Another clean approach without using Swtich case:

var ProtocolAndFileMappings = new Dictionary<string, string>()
    {
       {"email json","Očitanje.json"},
       {"email text","Očitanje.json"},
       {"email png","Očitanje.png"},
       {"email Jpeg","Očitanje.Jpeg"}
     };

 builder.Attachments.Add(ProtocolAndFileMappings[data.Subscriber.Protocol], CraftAttachment(data));

CodePudding user response:

Another approach using a local function to simplify the call:

void add(string s) => if (s != null) builder.Attachments.Add(s, CraftAttachment(data));

add( data.Subscriber.Protocol switch
{
    "email json" => "Očitanje.json",
    "email text" => "Očitanje.txt",
    _ => null
});

(Although I think that some folks would criticize that as "too cute...)

NOTE: This solution (like the other solutions) suffers from a drawback.

The code will always make an additional test against null, which the straightforward switch doesn't do - so this is (very marginally) less efficient.

I personally would do it like this (which avoids the drawback):

void add(string s) => builder.Attachments.Add(s, CraftAttachment(data));

switch (data.Subscriber.Protocol)
{
    case "email json": add("Očitanje.json"); break;
    case "email text": add("Očitanje.txt")   break;
    default:           /* Do nothing */      break;
}    

Simple local functions like that are very likely to be inlined by the JIT compiler, so there should be no overhead.

  • Related