Make a default indexer property for a class in C#

Classes such as Dictionary and List provide indexer properties that let you access values as if the object were an array. For example, the following code sets and then gets a last name from a Dictionary.

Dictionary names = new Dictionary();
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
{
// Store items here.
private Dictionary Entries
= new Dictionary();

// 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 key (the index) is in the Dictionary or the default value otherwise. The set method simply saves the key/value pair in the Dictionary.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.