I am trying to make an API, one function in that API takes Enum as parameter which then corresponds to a string which is used.
public enum PackageUnitOfMeasurement
{
LBS,
KGS,
};
The trivial method to code this will have to list every case in code. But as their are 30 cases so I am trying to avoid that and use Dictionary Data Structure, but I can’t seem to connect the dots on how will I relate value to enum.
if(unit == PackageUnitOfMeasurement.LBS)
uom.Code = "02"; //Please note this value has to be string
else if (unit == PackageUnitOfMeasurement.KGS)
uom.Code = "03";
Here is one way you could store the mapping in a dictionary and retrieve values later:
Another option is to use something like the
DecriptionAttributeto decorate each enumeration item and use reflection to read these out, as described in Getting attributes of Enum’s value:The benefit of the second approach is that you keep the mapping close to the enum and if either changes, you don’t need to hunt for any other place you need to update.