Make a default indexer property for a class in C#

[default indexer]

Classes such as Dictionary and List provide a default indexer property that lets you access values using a syntax similar to the one you use to access values in an array. For example, the following code sets and then gets a last name from a Dictionary.

Dictionary<string, string> names =
    new Dictionary<string, string>();
names["Rod"] = "Stephens";
MessageBox.Show(names["Rod"]);

You can add similar functionality to your class by giving it a property named this. It should take a special parameter in square brackets that gives the index that the property should use to get or set the value.

This example makes a DictionaryWithDefault class. This class is basically a wrapper for Dictionary but it returns a default value if you try to access a key that isn’t in the Dictionary. The following code shows how the class works.

class DictionaryWithDefault<TKey, TValue>
{
    // Store items here.
    private Dictionary<TKey, TValue> Entries
        = new Dictionary<TKey, TValue>(); 

    // The default value.
    private TValue DefaultValue;

    // Constructor.
    public DictionaryWithDefault(TValue default_value)
    {
        DefaultValue = default_value;
    }

    // Make the indexer property.
    public TValue this[TKey key]
    {
        get
        {
            // Return the value for this key or the default value.
            if (Entries.ContainsKey(key)) return Entries[key];
            return DefaultValue;
        }
        set
        {
            // Set the property's value for the key.
            Entries.Add(key, value);
        }
    }
}

This is a generic class with type parameters TKey and TValue. Most of the code is relatively straightforward (if you understand generic classes).

The interesting part is the indexer property. The get method returns the appropriate value if the index is in the Dictionary or the default value otherwise. The set method simply saves the key/value pair in the Dictionary.

The following code shows how the example program uses the DictionaryWithDefault class.

private void Form1_Load(object sender, EventArgs e)
{
    // Make a dictionary.
    DictionaryWithDefault<string, string> dict =
        new DictionaryWithDefault<string, string>("<Missing>");

    // Add some items to the dictionary.
    dict["Ann"] = "Archer";
    dict["Chuck"] = "Cider";
    dict["Dora"] = "Deevers";

    // Display some values.
    lstNames.Items.Add("Ann" + " " + dict["Ann"]);
    lstNames.Items.Add("Ben" + " " + dict["Ben"]);
    lstNames.Items.Add("Chuck" + " " + dict["Chuck"]);
    lstNames.Items.Add("Dora" + " " + dict["Dora"]);
    lstNames.Items.Add("Ed" + " " + dict["Ed"]);
}

This code creates a new DictionaryWithDefault object and adds three key/value pairs to it. It then fetches five values from it and adds the keys and values to a ListBox. The dictionary returns the default value for Ben and Ed because those keys weren’t added to the dictionary.


Download Example   Follow me on Twitter   RSS feed   Donate








This entry was posted in classes, OOP and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *