Associated Objects in C#
objc_setAssociatedObject makes a friend
Many people think there is no equivalent of objc_setAssociatedObject in C#, but those people are wrong.
As a quick refresher, Objective-C allows you to add methods to objects via categories (roughly equivalent to extension methods in C#), but there's no way to add new property values directly. Instead, you can use objc_setAssociatedObject
and objc_getAssociatedObject
to store the values. The real benefit is that the value will use the reference policy you specify (e.g. OBJC_ASSOCIATION_RETAIN_NONATOMIC
for a strong reference) and the associated object will get cleaned up when the target object is deallocated.
As of .Net 4.5, there is a new class called ConditionalWeakMap<T,K>
that performs a similar function in C#. The key is the object you want to associate something to and the value is the object to be associated. You can only store one value, but that's not terribly difficult to handle and totally thread-safe if you use ConcurrentDictionary<T,K>
as the value. (ConditionalWeakMap itself is thread-safe)
The real value of ConditionalWeakMap is how it interacts with the garbage collector. The key is a weak reference, so when the key object is garbage collected, the reference to the value object is released. But its even better than that. No references in the entire object graph of value count toward keeping objects alive when the garbage collector sweeps the heap. That means as long as you aren't keeping references to those objects somewhere else, the associated object(s) will be garbage collected when the key object is collected, even if the key and value objects have circular references to each other and no matter how deep the graph goes on the value object!
How cute... objc_getAssociatedObject
made a new friend. 💖
This blog represents my own personal opinion and is not endorsed by my employer.