I have an enum representing all material assembly codes in the system:
public enum EAssemblyUnit
{
[Description("UCAL1")]
eUCAL1,
[Description("UCAL1-3CP")]
eUCAL13CP,
[Description("UCAL40-3CP")]
eUCAL403CP, // ...
}
In legacy code in another part of the system, I have objects labeled with strings that match the enum descriptions. Given one of those strings, what’s the cleanest way to get the enum value? I envision something like:
public EAssemblyUnit FromDescription(string AU)
{
EAssemblyUnit eAU = <value we find with description matching AU>
return eAU;
}
You’d need to iterate through all the static fields of the enum (that’s how they’re stored in reflection) finding the Description attribute for each one… when you spot the right one, get the value of the field.
For example:
(This is generic just to make it reusable for different enums.)
Obviously you’d want to cache the descriptions if you’re doing this even slightly frequently, e.g.: