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() && (attributes.First() as DescriptionAttribute) != null)
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 return (T)type.GetFields(BindingFlags.Public | BindingFlags.Static).FirstOrDefault().GetValue(null);
76 //throw new ArgumentException($"{description} can't be found.", "Description");
80 /// Get the numeric value from string representation of the name.
82 /// <typeparam name="T"></typeparam>
83 /// <param name="value"></param>
84 /// <returns>The numeric value.</returns>
85 public static T GetValue<T>(this string value) where T : struct
88 if (Enum.TryParse(value, true, out result))
93 throw new ArgumentException($"{value} can't be found.", nameof(value));