Getting an attribute of an enum with reflection and caching it

suggest change

Attributes can denote metadata on enum fields. Reading them with reflection is relatively slow, so cache the result. This helper fails for a combined flags value, because ToString() is then not a single field name. The cache is not safe for concurrent callers.

private static Dictionary<object, object> attributeCache = new Dictionary<object, object>();

public static T GetAttribute<T, V>(this V value)
    where T : Attribute
    where V : struct
{
    object temp;

    // Try to get the value from the static cache.
    if (attributeCache.TryGetValue(value, out temp))
    {
        return (T) temp;
    }
    else
    {
        // Get the type of the struct passed in.
        Type type = value.GetType();   
        FieldInfo fieldInfo = type.GetField(value.ToString());

        // Get the custom attributes of the type desired found on the struct.
        T[] attribs = (T[])fieldInfo.GetCustomAttributes(typeof(T), false);

        // Return the first if there was a match.
        var result = attribs.Length > 0 ? attribs[0] : null;

        // Cache the result so future checks won't need reflection.
        attributeCache.Add(value, result);

        return result;
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents