Get Enum from Description Attribute

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 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

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.

Get enum description attribute from enum in c# using f# extension

I can't get it to work either, but you can rewrite the F# method to:

[<Extension>]
type Extensions =
[<Extension>]
static member inline GetEnumDescription(enum:'TEnum when 'TEnum :> Enum) : string =

let attributes = enum.GetType().GetField(enum.ToString()).GetCustomAttributes(typeof<DescriptionAttribute>, false)
match attributes.Length with
| x when x > 0 -> attributes.[0] |> (fun a -> a :?> DescriptionAttribute) |> fun a -> a.Description
| _ -> raise (InvalidOperationException("DescriptionAttribute is missing"))

You'll then get the Description property from the DescriptionAttributes when calling from C#:

  string result = Service.Unknown.GetEnumDescription();
Console.WriteLine(result);

Add description attribute to enum and read this description in TypeScript

Another interesting solution found here is using ES6 Map:

export enum Sample {
V,
IV,
III
}

export const SampleLabel = new Map<number, string>([
[Sample.V, 'FIVE'],
[Sample.IV, 'FOUR'],
[Sample.III, 'THREE']
]);

USE

console.log(SampleLabel.get(Sample.IV)); // FOUR

SampleLabel.forEach((label, value) => {
console.log(label, value);
});

// FIVE 0
// FOUR 1
// THREE 2

Convert Enum with [DescriptionAttribute] to Dictionary string,int

According to an answer https://stackoverflow.com/a/2650090/643095,

string description = Enumerations.GetEnumDescription((MyEnum)value);

Where value is int enum value.

You can use something like this:

accountViewModel.Genders = Enum.GetValues(typeof(Account.Genders))
.Cast<Account.Genders>()
.ToDictionary(t => Enumerations.GetEnumDescription((Genders)t), t => (int)t);

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



Related Topics



Leave a reply



Submit