Multiprocotol Terminalprogram (BAT)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
MultiTerm/Common/Helpers/EnumHelpers.cs

48 lines
1.7 KiB

using System.ComponentModel;
using System.Reflection;
namespace Common.Helpers;
public static class EnumHelpers
{
/// <summary>
/// Parse enum from string to enum type.
/// </summary>
/// <typeparam name="T">type of the enum</typeparam>
/// <param name="value">value to parse to enum</param>
/// <returns>returns enum object with value</returns>
public static T ParseEnum<T>(string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
/// <summary>
/// Gets the description of an Enum value.
/// If there is no Description set, the Enum Value will be converted to string.
/// </summary>
/// <param name="enumObject">Enum Object to get Description of.</param>
/// <returns>String with Content of DescriptionAttribute of Enum object.</returns>
public static string GetEnumDescription(Enum enumObject)
{
// guard argument null
if (enumObject == null) { throw new ArgumentNullException(nameof(enumObject)); }
// get field info from enum type
FieldInfo? fieldInfo = enumObject.GetType().GetField(enumObject.ToString());
// return string of enum value if there is no field info
if (fieldInfo == null)
{
return enumObject.ToString();
}
// get description attribute and return if it is present
DescriptionAttribute? descAttrib = (DescriptionAttribute?)fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute), true);
if (descAttrib != null)
{
return descAttrib.Description;
}
// if no description attribute was found => return string of enum value
return enumObject.ToString();
}
}