0

I have below enum and I want to fetch its element's Display attribute based on values assigned to it.

I need to create a function where I need to pass a value(1 for Economic) and it will return me related element's Display attribute.

public enum ProbabilityNames
{
    [Display(Name = "Economic Probability")]
    Economic = 1,
    [Display(Name = "Reliability Probability")]
    Reliability = 2     
}
Sunil Bamal
  • 87
  • 1
  • 14
  • Does this answer your question? [Reflection - get attribute name and value on property](https://stackoverflow.com/questions/6637679/reflection-get-attribute-name-and-value-on-property) – Ali Bigdeli Jul 28 '20 at 16:18
  • You can use `Description` attribute instead of `Display` and get fetch that as mentioned here: https://stackoverflow.com/questions/1799370/getting-attributes-of-enums-value – Süleyman Sümertaş Jul 28 '20 at 16:24

1 Answers1

1

You can use reflection for that:

public static class ProbabilityNamesExtensions
{
    public static DisplayAttribute GetDisplay(this ProbabilityNames value) =>
        typeof(ProbabilityNames)
            .GetField(Enum.GetName(typeof(ProbabilityNames), value))
            .GetCustomAttributes(false)
            .SingleOrDefault(attr => attr is DisplayAttribute) as DisplayAttribute;

    public static string GetDisplayName(this ProbabilityNames value) =>
        value.GetDisplay()?.Name;
}

You can use it like this:

ProbabilityNames.Economic.GetDisplay();

Or if you need to get the display based on an int value, you can just cast it:

((ProbabilityNames)1).GetDisplay();
rytisk
  • 1,331
  • 2
  • 12
  • 19
  • thanks @rytisk, it working, great work..best thing is you added an extension method to enum – Sunil Bamal Jul 29 '20 at 07:32
  • just one request if you can add exception handling and can return empty string in exception occurs(in case if we pass wrong int value which does not exists).. – Sunil Bamal Jul 29 '20 at 07:41