Posts

Showing posts from March, 2011

C# Mixins With State

With the C# quasi-mixin pattern , one of the biggest limitations is that the mixins can't introduce state to a class. An alternative was for the mixin interface to require the composing classes to implement a property that the mixin would use as its own, as demonstrated in this example . In the .NET Framework 4.0, the ConditionalWeakTable<TKey, TValue> class can be used to associate arbitrary state to any instance. It's thread safe and it keeps a dictionary of weak references from the target instance to its associated state. If a target instance has no references outside the conditional weak table, then it can be reclaimed by the garbage collector. When that happens, its entry in the table is removed. This makes it possible for a mixin-like class to maintain state for the instances it extends. Let's look at a mixin for a message container: public enum MessageType { Error, Warning, Info } public class Message { public readonly MessageType Type;...