I want to increment integer members of an object using Interlocked.Increment, but I want to reference those integers via reflection. Example code I have, which is not working, is below.
public class StatBoard
{
#region States (count of)
public int Active;
public int Contacting;
public int Polling;
public int Connected;
public int Waiting;
public int Idle;
#endregion
protected IEnumerable<FieldInfo> states;
public StatBoard()
{
Type foo = GetType();
FieldInfo[] fields = foo.GetFields(BindingFlags.Instance & BindingFlags.Public);
states = from n in fields
where n.FieldType == typeof(int)
select n;
}
public void UpdateState(string key)
{
FieldInfo statusType = states.First(
i => i.Name == key
);
System.Threading.Interlocked.Increment(ref (int)statusType.GetValue(this));
}
}
How do I modify the UpdateState method to make this work?