{"id":2844,"date":"2019-11-12T16:17:49","date_gmt":"2019-11-12T15:17:49","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=2844"},"modified":"2022-07-25T08:33:24","modified_gmt":"2022-07-25T07:33:24","slug":"c-enum-helper","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/c-enum-helper\/","title":{"rendered":"C# Enum Helper"},"content":{"rendered":"\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"csharp\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\n\nnamespace Helpers\n{\n    public class EnumHelper\n    {\n        public static T ParseEnum&lt;T>(string value, T defaultValue) where T : struct, IConvertible\n        {\n            if (!typeof(T).IsEnum) throw new ArgumentException(\"T must be an enumerated type\");\n            if (string.IsNullOrEmpty(value)) return defaultValue;\n            if (!Enum.TryParse&lt;T>(value, out var enumValue)) return defaultValue;\n            return enumValue;\n        }\n        \n    \tpublic static string GetDescription&lt;T>(T enumValue) where T : struct, IConvertible\n    \t{\n    \t\tif (!typeof(T).IsEnum) return null;\n    \t\tvar description = enumValue.ToString();\n    \t\tvar fieldInfo = enumValue.GetType().GetField(enumValue.ToString());\n    \t\tif (fieldInfo != null)\n    \t\t{\n    \t\t\tvar attrs = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);\n    \t\t\tif (attrs != null &amp;&amp; attrs.Length > 0)\n    \t\t\t{\n    \t\t\t\tdescription = ((DescriptionAttribute)attrs[0]).Description;\n    \t\t\t}\n    \t\t}\n    \t\treturn description;\n    \t}\n\n        public static IEnumerable&lt;string> GetEnumDescriptionValues(Type enumType)\n        {\n            return Enum.GetNames(enumType)\n                .Select(x =>\n                {\n                    var attributes = enumType.GetField(x).GetCustomAttributes(true);\n                    var attribute = attributes.FirstOrDefault(a => a is DescriptionAttribute) as DescriptionAttribute;\n                    return attribute?.Description ?? x;\n                });\n        }\n\n        public static T ParseEnumDescriptionValues&lt;T>(string value) where T : IConvertible\n        {\n            value = value?.ToLowerInvariant()?.Trim();\n            var enumType = typeof(T);\n            Dictionary&lt;string, int> d = GetEnumDict(enumType);\n            var result = d.ContainsKey(value) ? d[value] : 0;\n            return (T)Convert.ChangeType(result, Enum.GetUnderlyingType(typeof(T)));\n        }\n\n        private static Dictionary&lt;string, int> GetEnumDict(Type enumType)\n        {\n            var d = new Dictionary&lt;string, int>();\n            Array.ForEach(Enum.GetNames(enumType), x =>\n            {\n                var v = Enum.Parse(enumType, x);\n                var i = (int)v;\n\n                d.Add(x.ToLowerInvariant(), i);\n\n                var attributes = enumType.GetField(x).GetCustomAttributes(true);\n                var attribute = attributes.FirstOrDefault(a => a is DescriptionAttribute) as DescriptionAttribute;\n                if (attribute != null &amp;&amp; !d.ContainsKey(attribute.Description))\n                    d.Add(attribute.Description?.ToLowerInvariant(), i);\n            });\n            return d;\n        }\n    }\n}\n<\/pre><\/div>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"csharp\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">public static class EnumUtils\n{\n\tpublic static T ParseEnum&lt;T>(string value, T defaultValue) where T : struct, IConvertible\n\t{\n\t\tif (!typeof(T).IsEnum) throw new ArgumentException(\"T must be an enumerated type\");\n\t\tif (string.IsNullOrEmpty(value)) return defaultValue;\n\t\tif (TryParseEnumDescriptionValues&lt;T>(value, out var enumValue)) \n\t\t{ \n\t\t\treturn enumValue;\n\t\t}\n\t\tif (Enum.TryParse&lt;T>(value, out var enumValue2))\n\t\t{\n\t\t\treturn enumValue2;\n\t\t}\n\t\treturn defaultValue;\n\t}\n\tpublic static bool TryParseEnumDescriptionValues&lt;T>(string inValue, out T value) where T : struct, IConvertible\n\t{\n\t\tvar items = GetEnumDescriptionValues&lt;T>();\n\t\tvar item = items.FirstOrDefault(x => StringHelper.Equals(x.Item1, inValue));\n\t\tif (item != null) { \n\t\t\tvalue = item.Item2;\n\t\t\treturn true; \n\t\t}\n\t\tvalue = default(T);\n\t\treturn false;\n\t}\n\tpublic static IEnumerable&lt;Tuple&lt;string, T>> GetEnumDescriptionValues&lt;T>() where T : struct, IConvertible\n\t{\n\t\tvar enumType = typeof(T);\n\t\treturn Enum.GetValues(enumType).Cast&lt;T>().Select(x => new Tuple&lt;string, T>(GetDescription(x) , x));\n\t}\n\tpublic static IEnumerable&lt;string> GetEnumDescriptionValues(Type enumType)\n\t{\n\t\treturn Enum.GetNames(enumType)\n\t\t\t.Select(x =>\n\t\t\t{\n\t\t\t\tvar attributes = enumType.GetField(x).GetCustomAttributes(true);\n\t\t\t\tvar attribute = attributes.FirstOrDefault(a => a is DescriptionAttribute) as DescriptionAttribute;\n\t\t\t\treturn attribute?.Description ?? x;\n\t\t\t});\n\t}\n\tpublic static string GetDescription&lt;T>(T enumValue) where T : struct, IConvertible\n\t{\n\t\tif (!typeof(T).IsEnum) return null;\n\t\tvar description = enumValue.ToString();\n\t\tvar fieldInfo = enumValue.GetType().GetField(enumValue.ToString());\n\t\tif (fieldInfo != null)\n\t\t{\n\t\t\tvar attrs = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);\n\t\t\tif (attrs != null &amp;&amp; attrs.Length > 0)\n\t\t\t{\n\t\t\t\tdescription = ((DescriptionAttribute)attrs[0]).Description;\n\t\t\t}\n\t\t}\n\t\treturn description;\n\t}\n}<\/pre><\/div>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[6,4,1],"tags":[],"class_list":["post-2844","post","type-post","status-publish","format-standard","hentry","category-dotnet","category-programming","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2844","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=2844"}],"version-history":[{"count":4,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2844\/revisions"}],"predecessor-version":[{"id":6119,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2844\/revisions\/6119"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=2844"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=2844"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=2844"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}