Reputation: 117
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
}
Upvotes: 0
Views: 171
Reputation: 1539
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();
Upvotes: 1