The missing Linq: Stateful extentions methods

time to read 2 min | 386 words

It seems to me that right now there is a lot of exploring going on with extention methods. People are doing some really cool stuff with them.

What I am afraid of is that this exploration is going to hit glass wall the moment people are going to try to do the interesting stuff with them. The reason for this is that beyond the simplest cases, I would really want to have some sort of a state between method calls.

Here is a code sample that demonstrate the issue:

object myRandomObj = new object();
myRandomObject.Tag("Linq ExtentionMethods");

Tag() and GetTags() are extention methods. The problem is that as it stands now, there isn't really a way to implement this functionality using Linq. You need to keep the tags associated with the object, which usually means that you will use a hash table. This seems like a solution, but it runs into the issue of breaking the GC, since I would like to have the state freed by the GC when the object goes out of scope.

Hashtable based on WeakReference are one solution to this, but this is quite a bit more complex than it sounds, and you needs to scavengar that table every now and then, which means that you can either suffer wasted memory(bad) or have a separate thread that will clean the table (bad).

I can see two solutions to this problem. Either adding another field to System.Object "IDictionary ExtendedProperties" or supplying a weak hashtable implementation that ties into the GC in the same manner that WeakReference is there. The first solution is the simplest, but it is tying object into IDictionary, as well as increasing the size of System.Object significantly. The second solution is more complex, but it is much prefered, since it doesn't affect anything else. 

The problem is that both of those requires support at the framework level, it is not something that can be done externally.