Search code examples
c#.netreflectioncustom-attributes

How to get Custom Attribute values for enums?


I have an enum where each member has a custom attribute applied to it. How can I retrieve the value stored in each attribute?

Right now I do this:

var attributes = typeof ( EffectType ).GetCustomAttributes ( false );
foreach ( object attribute in attributes )
{
    GPUShaderAttribute attr = ( GPUShaderAttribute ) attribute;
    if ( attr != null )
        return attr.GPUShader;
}
return 0;

Another issue is, if it's not found, what should I return? 0 is implcity convertible to any enum, right? That's why I returned that.

Forgot to mention, the above code returns 0 for every enum member.


Solution

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