Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 bValue = property.Get();//returns the value of test.b
    property.Set(3);//sets test.a to 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading