How to write a getter and setter for a Dictionary?

Mausimo picture Mausimo · Jul 20, 2012 · Viewed 41k times · Source

How do you define a getter and setter for complex data types such as a dictionary?

public Dictionary<string, string> Users
{
    get
    {
        return m_Users;
    }

    set
    {
        m_Users = value;
    }
}

This returns the entire dictionary? Can you write the setter to look and see if a specific key-value pair exists and then if it doesn't, add it. Else update the current key value pair? For the get, can you return a specific key-value pair instead of the whole dictionary?

Answer

James Michael Hare picture James Michael Hare · Jul 20, 2012

Use an indexer property (MSDN):

public class YourClass
{
    private readonly IDictionary<string, string> _yourDictionary = new Dictionary<string, string>();

    public string this[string key]
    {
        // returns value if exists
        get { return _yourDictionary[key]; }

        // updates if exists, adds if doesn't exist
        set { _yourDictionary[key] = value; }
    }
}

Then use like:

var test = new YourClass();
test["Item1"] = "Value1";