Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching meta-information to an object in .NET

Tags:

.net

I'm pretty sure this is a duplicate question, but I can't find the original(s).

I am getting some objects that I need to "attach" some information to. Basically, if that object ever gets back to the same piece of code, I need to see that I have seen it before.

ie. something like this:

Dictionary<WeakReference<ObjectType>, string> _Cache;

Note the weak reference in there (I know WeakReference is not generic btw), I need to make the key of the cache a weak reference, to handle the fact that the objects are GC'ed out of my control.

Now, I can make that cache full of weak references, but I seem to recall a similar type of system already existing in .NET, which was GC'ed automatically alongside the object.

Note that I do not recall the overhead of this, so I will make sure to read up on the subject before deciding if this is a good/better solution than my own cache. Unfortunately I cannot change the object in question, so I need to keep track of this meta-information somewhere else.

My limitations:

  • The object is not mine, so I cannot change it in any way possible
  • I cannot inherit from the object, as it is sealed, besides, I'm given the objects, I do not construct them, so I would have to be able to replace an instance with a new object of a descendant type for this to be useful
  • The objects are GC'ed out of my control, so I cannot just use a dictionary, which will slowly fill up, either with "references" to nonexistant objects, or will hold on to the objects, I would need a dictionary with a weak referenced key (thus: custom dictionary)
  • The objects, although I could encapsulate them within my own code and thus carry alongside it the required information, is passed back to a framework out of my control, and given back to me from the same, and thus I need to be able to retrieve/look up the old information with just the object in question

Basically, something like:

PropertyAttacher.Attach(instance, "Name", name);

Do I remember correctly? What are the classes involved?

like image 382
Lasse V. Karlsen Avatar asked Jan 05 '12 14:01

Lasse V. Karlsen


2 Answers

You may be looking for .NET 4's ConditionalWeakTable<TKey, TValue>

like image 66
Simon Mourier Avatar answered Nov 05 '22 18:11

Simon Mourier


Maybe you can build a dictionnary indexed by RuntimeHelpers.GetHashCode.

From MSDN:

RuntimeHelpers.GetHashCode is useful in scenarios where you care about object identity. Two strings with identical contents will return different values for RuntimeHelpers.GetHashCode, because they are different string objects, although their contents are the same.

EDIT: @Simon Mourier's solution seems to be a much better one.

like image 42
user703016 Avatar answered Nov 05 '22 20:11

user703016