You can use DescriptionAttribute
, from System.ComponentModel
, to query attributes of an enum value.
In the code below GetEnumDescription
demonstrates the usage of DescriptionAttribute
. It can be used to get the description of any enum value. It also falls back to the enum value itself in case a description is not available.
Code example:
using System;
using System.ComponentModel;
using System.Linq;
public class Program
{
public static string GetEnumDescription(Enum value)
{
if (value == null) { return ""; }
DescriptionAttribute attribute = value.GetType()
.GetField(value.ToString())
?.GetCustomAttributes(typeof(DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
public enum FeeNameEnum
{
[Description("Account Opening Fee description (...)")]
AccountOpeningFee,
}
public static void Main(String[] args)
{
FeeNameEnum e = FeeNameEnum.AccountOpeningFee;
Console.WriteLine(GetEnumDescription(e));
}
}
Output:
Account Opening Fee description (...)
Usage in your code:
In your actual code you can add GetEnumDescription
(and using System.ComponentModel;
), then change the FeeNameName
property from:
public string FeeNameName { get { return FeeName.ToString(); } }
To:
public string FeeNameName { get { return GetEnumDescription(FeeName); } }
In case you encounter errors, you can use this version of GetEnumDescription
which is doing it step by step and so might help to identify where the problem comes from:
public static string GetEnumDescription1(Enum value)
{
if (value == null) { return ""; }
var type = value.GetType();
var field = type.GetField(value.ToString());
var custAttr = field?.GetCustomAttributes(typeof(DescriptionAttribute), false);
DescriptionAttribute attribute = custAttr?.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
Note: the argument passed to the value
parameter above is expected to be either a simple valid enum value, or a flag composite - "or" (|
) of several values.