Here is a class that lets us add a Tag property to any object without using AOP.
static class ExtensionMethods
{
private static Dictionary<WeakReference, object> tags =
new Dictionary<WeakReference, object>();
public static void SetTag(this object obj, object tagValue)
{
Cleanup();
var found = tags.Select(o => o.Key)
.Where(k => ReferenceEquals(obj, k.Target));
if (found.Count() > 0)
{
tags[found.Single()] = tagValue;
}
else
tags[new WeakReference(obj)] = tagValue;
}
public static T GetTag<T>(this object obj)
{
return (T)tags.Where(o => ReferenceEquals(o.Key.Target, obj)).First().Value;
}
private static void Cleanup()
{
var toRemove = tags.Select(o => o.Key).Where(p => !p.IsAlive);
foreach (var tr in toRemove)
tags.Remove(tr);
}
}