Search code examples
c#reflectionsystem.reflection

how to cache reflection in C#


Hello there I am familiar with reflection quite a bit, I have been through loads of examples and I know how it works and for what purpose we can use it. But I didn't get any examples of caching the reflection, neither do I know what does it mean. And somehow I have to use caching of reflection in of the projects that I am doing.

Therefore, I would be obliged if some one can briefly explain this concept as well as give some examples of it, a link to existing examples would also be appreciated. And please also describe the reflection of attributes as well as its caching. Thanks in advance.

Regards Umair


Solution

  • You would cache it like you would anything else:

     var cache = new Dictionary<Type, IEnumerable<Attribute>>();
    
     // obj is some object
     var type = obj.GetType();
     var attributes = type.GetCustomAttributes(typeof(MyAttribute), true);
     cache.Add(type, attributes);