views:

35

answers:

1

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?

+1  A: 

This cannot work by design. An int is a value type. The GetValue() method returns a copy of the int. You'll increment that copy, not the original. Reflection doesn't have any way to get a reference to a value type value.

Hans Passant
He could use `Reflection.Emit` in a `DynamicMethod` to access the field type. It would be complex and slow, though.
Stephen Cleary