Everything about my daily life as a programmer/Electrical Engineer!

State Bag for all objects

Extension methods are very powerful, but sometimes you need to store state on the object you are processing in an extension method.  The problem is implementing state maintenance in a static method can be a real chore.  Not to mention when you only want to track state on an object you can’t.  I wrote this quick and dirty state maintenance set of extension methods.  There is a caveat that I cannot fix at the time of writing. 

 

If you store data in the statebag, you need someway of knowing when the object is getting destroyed so that you can manually call ClearVariables.  If you do not clear the variables the values will be left in the statebag FOREVER causing massive memory leaks!  I would like a way to alleviate this if anyone has any ideas.

 

using System;
using System.Collections.Generic;

namespace StateBagTest
{
class Program
{
static void Main(string[] args)
{
object o = new object();
o.Set("newvar", 5);
int number = (int)o.Get("newvar");
o.ClearVariables(); //very very important!
Console.ReadLine();
}

}

public static class StateBag
{
static Dictionary<int, Dictionary<string, object>> _stateBag = new Dictionary<int, Dictionary<string, object>>();
public static void Set(this object obj, string var, object value)
{
int hashcode = obj.GetHashCode();
if (!_stateBag.ContainsKey(hashcode))
{
_stateBag.Add(hashcode, new Dictionary<string, object>());
}
_stateBag[hashcode][var] = value;
}

public static object Get(this object obj, string var)
{
int hashcode = obj.GetHashCode();
if (_stateBag.ContainsKey(hashcode) && _stateBag[hashcode].ContainsKey(var))
{
return _stateBag[hashcode][var];
}
return null;
}

//Really need to call this when your object is done using the state bag, which may be hard for some objects you are extending!
public static void ClearVariables(this object obj)
{
int hashcode = obj.GetHashCode();
if (_stateBag.ContainsKey(hashcode))
{
_stateBag[hashcode] = null;
}
}
}
}