Safe Index Property Accessor

By | June 25, 2014

Recently I had to build a very dynamic DataGrid in WPF, in which the columns were constructed dynamically. And some rows did not contain data for each generated column. I stored the dynamic values in a dictionary and bound the dynamic columns to the indexer property. The problem was that the dictionary throw an KeyNotFoundException when the UI binding tried to get a value for a key which does not exist in a certain model. To “suppress” the exception I wrote a dictionary which checks if the key/index exists. If not, the default value is returned.

Pretty easy code. The class is called IndexAccessorSafeDictionary

public class IndexAccessorSafeDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    public new TValue this[TKey key]
    {
        get
        {
            if (!this.ContainsKey(key))
                return default(TValue);
            return base[key];
        }
    }

    public TValue this[int index]
    {
        get
        {
            if (index >= this.Count)
                return default(TValue);
            return this.Skip(index).First().Value;
        }
    }
}

Leave a Reply

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


five × 3 =