Accessing and caching attributes I have the following manager class that handles access and caching attributes from classes. I am a bit worried about the caching mechanism.

Is there a better way of handling it?

public static class AttributeManager
    {
        private static Dictionary&lt;Type, Attribute&gt; _cache = new Dictionary&lt;Type, Attribute&gt;();

        public static AttributeType GetAttribute&lt;AttributeType&gt;(Type type)
            where AttributeType : Attribute
        {

            if (_cache.ContainsKey(type))
            {
                return (AttributeType)_cache[type];
            }

            var attr = Attribute.GetCustomAttribute(type, typeof(AttributeType));

            if (attr != null)
            {
                _cache.Add(type, attr);
                return (AttributeType)attr;
            }
            else
            {
                throw new ArgumentException($"The specified attribute: {nameof(AttributeType)} was not found.");
            }
        }
    }
Let’s define an extension method on Type:

public static class AttributeCache
{
    public static IEnumerable&lt;T&gt; Attributes&lt;T&gt;(this Type type)
        where T : Attribute =&gt; Cache
            .GetOrAdd(type, t =&gt; t.GetCustomAttributes(true).OfType&lt;Attribute&gt;().ToArray())
            .OfType&lt;T&gt;();        

    static ConcurrentDictionary&lt;Type, Attribute[]&gt; Cache { get; } = 
        new ConcurrentDictionary&lt;Type, Attribute[]&gt;();
}


Demo:

foreach (var a in typeof(MyCass).Attributes&lt;TestAttribute&gt;())
    Console.WriteLine(a.MyProp);