I’m marking my enums with an own entity attribute used to map the enums to the corresponding field in a case management system.
Getting the correct string from an enum value works fine, but how can I generate an enum from a string?
I started by doing this:
foreach (var fieldInfo in enumType.GetFields())
{
var attribute = (EntityNameAttribute)fieldInfo
.GetCustomAttributes(typeof (EntityNameAttribute), false)
.FirstOrDefault();
if (attribute == null)
continue;
if (attribute.Name != name)
continue;
//got a match. But now what?
}
But how do I get the proper value from a field? Can I just use fieldInfo.GetValue? If so, what instance should I use? Should the enum be treated as a static type?
Yes, you can use:
They’re just static readonly fields, effectively. Note that that isn’t getting an enum from a string… but if you do need to do that, you can use
Enum.Parse.One thing to note – if you’re using .NET 3.5, your whole code can be simplified with LINQ:
(That’s assuming that if there are multiple attributes of the right type defined, you don’t care which one has the right name, and only one will have the right name.)