2 * Copyright(c) 2019 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 using System.ComponentModel;
21 using System.Reflection;
28 internal static class EnumHelper
31 /// Get the description from the numeric value.
33 /// <typeparam name="T"></typeparam>
34 /// <param name="value"></param>
35 /// <returns>The description of the numeric value.</returns>
36 public static string GetDescription<T>(this T value) where T : struct
38 string result = value.ToString();
39 FieldInfo info = typeof(T).GetField(result);
40 var attributes = info.GetCustomAttributes(typeof(DescriptionAttribute), true);
41 if (null != attributes?.FirstOrDefault())
43 result = (attributes.First() as DescriptionAttribute).Description;
50 /// Get the numeric value from the description.
52 /// <typeparam name="T"></typeparam>
53 /// <param name="description"></param>
54 /// <returns>The numeric value.</returns>
55 public static T GetValueByDescription<T>(this string description) where T : struct
57 Type type = typeof(T);
58 foreach (var field in type.GetFields())
60 if (description == field.Name)
62 return (T)field.GetValue(null);
65 var attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), true);
66 if (null != attributes?.FirstOrDefault())
68 if (description == attributes.First().Description)
70 return (T)field.GetValue(null);
75 throw new ArgumentException($"{description} can't be found.", "Description");
79 /// Get the numeric value from string representation of the name.
81 /// <typeparam name="T"></typeparam>
82 /// <param name="value"></param>
83 /// <returns>The numeric value.</returns>
84 public static T GetValue<T>(this string value) where T : struct
87 if (Enum.TryParse(value, true, out result))
92 throw new ArgumentException($"{value} can't be found.", "Value");