Search code examples
c#dictionarygettersetter

Dictionary that points to getters/setters


Is it possible to make a dictionary that points to getters & setters?

For example:

public class test
{
  public Dictionary<string, int> pointer = new Dictionary<string,int>()
  {
    { "a", a }
  }; // the goal is to do pointer["a"] = someInt or print(pointer[a])
  
  public int a { get { return b;} set { b = 2; } }
  public int b;
}

Solution

  • Odds are you are not actually trying to put getters and setters in a dictionary, and that you are trying to access properties by their names. This is easily possible through Reflection. If that is what your question is about you should mark this as duplicate and close the question.

    But, the answer to your actual question is yes. It is possible to make a dictionary that points to getters and setters. You will need to use some lambda programming. Here is one way to do it:

    public class test
    {
        public Dictionary<string, GetSet<int>> pointer;
    
        public test()
        {
            pointer = new Dictionary<string, GetSet<int>>()
            {
                { "a", new(()=>a,i=>a = i) }
            };
        }
    
        public int a { get { return b; } set { b = 2; } }
        public int b;
    }
    
    public class GetSet<T>
    {
        private readonly Func<T> _get;
        private readonly Action<T> _set;
    
        public GetSet(Func<T> get, Action<T> set)
        {
            _get = get;
            _set = set;
        }
    
        public T Get() => _get();
        public void Set(T value) => _set(value);
    }
    

    Usage:

        var test = new test();
        var property = test.pointer["a"];
        var value = property.Get();//returns the value of test.a
        property.Set(3);//sets test.a to 3