When handling the values of an enum on a case by case basis, is it better to use a switch statement or a dictionary?
I would think that the dictionary would be faster.
It really depends on your scenario but, as an alternative, you could just have an attribute containing the translated text.
public enum FruitType
{
[Description("Otra")]
Other,
[Description("Manzana")]
Apple,
[Description("Platano")]
Banana,
Mango,
[Description("Naranja")]
Orange
}
Then you can have a method to read the description
public static string GetTranslation(FruitType fruit)
{
var mi = typeof(FruitType).GetMember(fruit.ToString());
var attr = mi[0].GetCustomAttributes(typeof(DescriptionAttribute),false);
if (attr.Count() > 0)
return ((DescriptionAttribute)attr[0]).Description;
else
return fruit.ToString(); //if no description added, return the original fruit
}
So you can then call it like this
string translated = GetTranslation(FruitType.Apple);
Since it uses reflection, this is likely to be the least efficient but might be easier to maintain depending on your situation and, as Chris mentioned in the comments, may not have any noticeable impact depending on how often it's called. You can swap Description
for a custom attribute of course. Just another option for you to consider :)