Getting Attributes of Enum'S Value

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()
}

How to get Custom Attribute values for enums?

It is a bit messy to do what you are trying to do as you have to use reflection:

public GPUShaderAttribute GetGPUShader(EffectType effectType)
{
MemberInfo memberInfo = typeof(EffectType).GetMember(effectType.ToString())
.FirstOrDefault();

if (memberInfo != null)
{
GPUShaderAttribute attribute = (GPUShaderAttribute)
memberInfo.GetCustomAttributes(typeof(GPUShaderAttribute), false)
.FirstOrDefault();
return attribute;
}

return null;
}

This will return an instance of the GPUShaderAttribute that is relevant to the one marked up on the enum value of EffectType. You have to call it on a specific value of the EffectType enum:

GPUShaderAttribute attribute = GetGPUShader(EffectType.MyEffect);

Once you have the instance of the attribute, you can get the specific values out of it that are marked-up on the individual enum values.

How to get a custom attribute on enum by passing in the enum value and attribute type?

Something like this?

using System;
using System.ComponentModel;
using System.Reflection;

namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
var descriptionAttribute = MyEnum.A.GetAttribute<DescriptionAttribute>();
}
}

public static class EnumExtensions
{
public static T GetAttribute<T>(this Enum @enum) where T : Attribute
{
var type = @enum.GetType();
var name = Enum.GetName(type, @enum);
var field = type.GetField(name);
var attribute = field.GetCustomAttribute<T>();
return attribute;
}
}

public enum MyEnum
{
[Description("A")] A,
[Description("B")] B
}
}

Get property of custom attribute for enum

Since the attribute is attached to an enum field, you should apply GetCustomAttribute to FieldInfo:

var res = typeof(Books)
.GetField(nameof(Books.IndianInTheCupboard))
.GetCustomAttribute<BookDetails>(false)
.Author;

Since attribute type is known statically, applying generic version of the GetCustomAttribute<T> method yields better type safety for getting the Author attribute.

Demo.

How to get Enum value from String value of one of it's attributes

Solution:

@AllArgsConstructor
@Getter
public enum ExternalEnum {
enum1("red", "1"),
enum2("black", "2"),
enum3("blue", "3");

private String colour;
private String number;

// you can call this method with number or name but you have to change
//parameter accordingly
public static ExternalEnum findByNumber(String number) {
for(ExternalEnum type : values()) {
if(type.equals(number)) {
return type;
}
}
}
}

Get attribute from Enum knowing only the PropertyInfo

An enum value is a static field of the enum type.

So once you have an enum value, you get the Type for the enum type, get the field info for the enum value, and get the attribute from the member info.

public static TAttributeType GetEnumValueAttribute<TAttributeType>(Enum val) 
where TAttributeType : Attribute
{
if (val == null)
{
return null;
}

return
val.GetType().
GetMember(val.ToString())?.
FirstOrDefault()?.
GetCustomAttribute<TAttributeType>();
}

And in your loop:

foreach (PropertyInfo pi in obj.GetType().GetProperties())
{
// get the attribute from the property, if it exists
AbbreviationAttribute attr = pi.GetCustomAttribute<AbbreviationAttribute>();

if (attr != null)
{
//append the value from the attribute, instead of the property name
values += $"{attr.Value}=";

// if property is an enum (nullable or otherwise)
if (pi.PropertyType.IsEnum || pi.PropertyType.IsNullableEnum())
{
values += $"{GetEnumValueAttribute<AbbreviationAttribute>((Enum)pi.GetValue(obj))?.Value};";
}
else
{
values += $"{pi.GetValue(obj)};";
}
}
}

You're really asking a duplicate of this question. I copied his code, but modernized it a bit.

C# - Getting all enums value by attribute

Something like this should get you on the way...

var enumValues = (from member in typeof(KodEnum).GetFields()
let att = member.GetCustomAttributes(false)
.OfType<EnumTypeAttribute>()
.FirstOrDefault()
where att != null && att.EnumType == "Task"
select member.GetValue(null))
.Cast<KodEnum>()
.ToList();

If you want the int value, then just cast it:

var enumValues = (from member in typeof(KodEnum).GetFields()
let att = member.GetCustomAttributes(false)
.OfType<EnumTypeAttribute>()
.FirstOrDefault()
where att != null && att.EnumType == "Task"
select (int)member.GetValue(null))
.ToList();

And all-lambda solution:

        var enumValues = typeof(KodEnum)
.GetFields()
.Select(x => new
{
att = x.GetCustomAttributes(false)
.OfType<EnumTypeAttribute>()
.FirstOrDefault(),
member = x
})
.Where(x => x.att != null && x.att.EnumType == "Task")
.Select(x => (int)x.member.GetValue(null))
.ToList();

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



Leave a reply



Submit