1: public static T FromDescription(this string description)
2: {
3: var type = typeof(T;
4: if (!type.IsEnum)
5: {
6: throw new InvalidOperationException($"{description} does not match any of the enumeration values);
7: }
8:
9: foreach (var field in type.GetFields())
10: {
11: if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
12: {
13: if (attribute.Description == description)
14: {
15: return (T)field.GetValue(null);
16: }
17: }
18: else
19: {
20: if (field.Name == description)
21: {
22: return (T)field.GetValue(null);
23: }
24: }
25: }
26:
27: throw new InvalidOperationException($"{description} does not match any of the enumeration values);
28: }
Now that we have the extension method we can invoke it on any string, like this:
var contactType = "Phone Call".FromDescription<ContactTypes>();
No comments:
Post a Comment