How to write a getter and setter for a Dictionary?

c#, dictionary, getter-setter

Solution

It is not possible to do it in a way that would involve only properties. You theoretically could write a setter, but for a getter, you would need to specify a key that you want to retrieve. That is impossible since properties do not accept parameters. Natural way to accomplish what you want would be to use methods:

private Dictionary<string, string> users = new Dictionary<string, string>();

public void Set(string key, string value)
{
    if (users.ContainsKey(key))
    {
        users[key] = value;
    }
    else
    {
        users.Add(key, value);
    }
}

public string Get(string key)
{
    string result = null;

    if (users.ContainsKey(key))
    {
        result = users[key];
    }

    return result;
}

Alternatively, as others have already said, you could use indexers, but I've always found them a little cumbersome. But I guess it's just a matter of personal preference.

And just for the sake of completeness, this is how a setter could look like, although it's highly unusual and counter-intuitive to have such a property:

public KeyValuePair<string, string> Users
{
    set
    {
        Set(value.Key, value.Value);
    }
}

Internally, it uses the `Set` method from my previous snippet.

Problem

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?

Original source