Search code examples
c#.netpropertiesgetter-setter

How to set Dictionary as a property ? Give an example


I'm trying to use a dictionary as a class member. I want to use a property to get/set the key/value of the dictionary but I'm confused as how to use a dictionary as a property. Since there are 2 parts, I don't know how to setup the get/sets.


Solution

  • You could try this:

    class Example {
      private Dictionary<int,string> _map;
      public Dictionary<int,string> Map { get { return _map; } }
      public Example() { _map = new Dictionary<int,string>(); }
    }
    

    Implementation would go along the lines of:

    var e = new Example();
    e.Map[42] = "The Answer";