DEV Community

Discussion on: C# switch - Which variation do you prefer?

Collapse
 
peledzohar profile image
Zohar Peled • Edited

Michael B mentioned a dictionary option (though I don't know what it has to do with the strategy pattern) - and I second that - it's quite easy to do it like this:
(names are shortened for brevity - Never do that on actual code!)

private Dictionary<Cases, string> _dic = new Dictionary<Cases, string>()
{
    {Cases.One, "one to three"},
    {Cases.Two, "one to three"},
    // and so on...
}

string GetCorrespondingString(Cases input)
{
    return _dic.TryGetValue(input, out var result) ? 
        result : 
        throw new InvalidEnumArgumentException();
}

Since c# 7.0, you can throw an exception directly from inside a ternary condition because c# 7.0 supports throw expression.

However, the switch expression is a very powerful tool and has a potential to shorten and beautify what was once a big long mess of case: /* code */ break;

Collapse
 
riscie profile image
riscie

Thank you! I like the approach of using a dictionary. However this way you can not combine cases One to Three, right? In our example I would be fine with it, but If we would have many cases, I would kind of dislike it.

Collapse
 
peledzohar profile image
Zohar Peled

Yes, that will force you to write all the cases into the dictionary - and it is a shortcoming of this approach. There are advantages for both approaches, just choose the most appropriate one each time...