Get Enum from Description attribute
public static class EnumEx
{
public static T GetValueFromDescription<T>(string description) where T : Enum
{
foreach(var field in typeof(T).GetFields())
{
if (Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
{
if (attribute.Description == description)
return (T)field.GetValue(null);
}
else
{
if (field.Name == description)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", nameof(description));
// Or return default(T);
}
}
Usage:
var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");
Finding an enum value by its Description Attribute
Using the extension method described here :
Testing t = Enum.GetValues(typeof(Testing))
.Cast<Testing>()
.FirstOrDefault(v => v.GetDescription() == descriptionToMatch);
If no matching value is found, it will return (Testing)0
(you might want to define a None
member in your enum for this value)
Get Enum Value By Description
Rule f;
var type = typeof(Rule);
foreach (var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute != null)
{
if (attribute.Description == "description"){
f = (Rule)field.GetValue(null);
break;}
}
else
{
if (field.Name == "description"){
f = (Rule)field.GetValue(null);
break;}
}
}
ref: Get Enum from Description attribute
How to get C# Enum description from value?
int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);
The default underlying data type for an enum
in C# is an int
, you can just cast it.
Getting attributes of Enum's value
This should do what you need.
try
{
var enumType = typeof(FunkyAttributesEnum);
var memberInfos =
enumType.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());
var enumValueMemberInfo = memberInfos.FirstOrDefault(m =>
m.DeclaringType == enumType);
var valueAttributes =
enumValueMemberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
var description = ((DescriptionAttribute)valueAttributes[0]).Description;
}
catch
{
return FunkyAttributesEnum.NameWithoutSpaces1.ToString()
}
Can I get an enum value having a given description attribute using a generic function?
If the targetType
parameter in IValueConverter.Convert
is really only giving you Enum
, rather than the specific type of enumeration you need to convert to, then I don't think converting from the Description
value alone will be possible. Actually, it might not be reliable anyway, because nothing is stopping anyone from creating two different values in the same enumeration and giving them identical descriptions (thus resulting in ambiguity).
Here's my suggestion: Instead of returning a string
return a custom struct
. Something like this:
public struct EnumValue
{
public EnumValue(Enum value, string description)
{
Value = value;
Description = description;
}
public Enum Value { get; }
public string Description { get; }
public override string ToString()
{
return Description;
}
}
Returning something like the above instead of just the description string
value, will allow you to convert back to the enumeration value just by reading the Value
property.
(You could also go a step further and put the actual logic for retrieving the description into the EnumValue
struct, removing the description
parameter from the constructor.)
How can I get an enum value from its description?
You'd need to iterate through all the static fields of the enum (that's how they're stored in reflection) finding the Description attribute for each one... when you spot the right one, get the value of the field.
For example:
public static T GetValue<T>(string description)
{
foreach (var field in typeof(T).GetFields())
{
var descriptions = (DescriptionAttribute[])
field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (descriptions.Any(x => x.Description == description))
{
return (T) field.GetValue(null);
}
}
throw new SomeException("Description not found");
}
(This is generic just to make it reusable for different enums.)
Obviously you'd want to cache the descriptions if you're doing this even slightly frequently, e.g.:
public static class DescriptionDictionary<T> where T : struct
{
private static readonly Dictionary<string, T> Map =
new Dictionary<string, T>();
static DescriptionDictionary()
{
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException("Must only use with enums");
}
// Could do this with a LINQ query, admittedly...
foreach (var field in typeof(T).GetFields
(BindingFlags.Public | BindingFlags.Static))
{
T value = (T) field.GetValue(null);
foreach (var description in (DescriptionAttribute[])
field.GetCustomAttributes(typeof(DescriptionAttribute), false))
{
// TODO: Decide what to do if a description comes up
// more than once
Map[description.Description] = value;
}
}
}
public static T GetValue(string description)
{
T ret;
if (Map.TryGetValue(description, out ret))
{
return ret;
}
throw new WhateverException("Description not found");
}
}
Get Description Attributes From a Flagged Enum
HasFlag
is your friend. :-)
The extension method below uses the GetDescription extension method you've posted above, so ensure you have that. The following should then work:
public static List<string> GetDescriptionsAsText(this Enum yourEnum)
{
List<string> descriptions = new List<string>();
foreach (Enum enumValue in Enum.GetValues(yourEnum.GetType()))
{
if (yourEnum.HasFlag(enumValue))
{
descriptions.Add(enumValue.GetDescription());
}
}
return descriptions;
}
Note: HasFlag
allows you to compare a given Enum value against the flags defined. In your example, if you have
Result y = Result.Value1 | Result.Value2 | Result.Value4;
then
y.HasFlag(Result.Value1)
should be true, while
y.HasFlag(Result.Value3)
will be false.
See also: https://msdn.microsoft.com/en-us/library/system.enum.hasflag(v=vs.110).aspx
Related Topics
How to Make Multi-Language App in Winforms
C# List<String> to String with Delimiter
How to Resolve Ioptions Instance Inside Configureservices
Is There a Good Way to Convert Between Bitmapsource and Bitmap
C# Using Parameters.Addwithvalue in SQLdataadapter
Is Securestring Ever Practical in a C# Application
How to Get an Oauth 2.0 Authentication Token in C#
Implementing Zero or One to Zero or One Relationship in Ef Code First by Fluent API
Invalid Attempt to Read When No Data Is Present
Generic Method Executed with a Runtime Type
Nullable Type Is Not a Nullable Type
An ASP.NET Setting Has Been Detected That Does Not Apply in Integrated Managed Pipeline Mode
"Open/Close" SQLconnection or Keep Open
How to Hide Tabpage from Tabcontrol
Collection<T> Versus List<T> What Should You Use on Your Interfaces