I regret to inform you I have another cursed C# question

Short version: "What is the most performant way to associate a value with a type?"

Long version: I created a custom System.Attribute; I attached it to several of my classes The first time I reflect on such a class's attributes, I want to create several cached values derived from those attributes, and store them where I can get them the next time I reflect. But turns out System.Attribute.GetCustomAttributes creates a new object each time…

Things I have considered:

- Make a big Dictionary mapping class fully qualified name to my cached-values-related-to-type object. (This is what we're doing now. I hate it.)

- Add a member to every class with the attribute (coincidentally, they all inherit from the same interface), and store the cached-values obj there. (Memory inefficient?)

- ???

I know there's some way for attributes to be combined with code generation. So if a class has an attribute, I can silently add statics on it or ???

Follow

@mcc

No need to use the type name: map the Type object you get from typeof() to the attribute value; GetHashCode() on that is cheaper than going via the string.

Then you can hide the details in an extension method on IParent to automatically grab the attr object from the cache, generating it if it doesn't exist.

Sign in to participate in the conversation
Mastodon

a Schelling point for those who seek one