using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MBS.Framework.Collections.Generic
{
///
/// Provides a that automatically adds or updates a key or value when
/// it is requested.
///
/// The type of the key part of the dictionary.
/// The type of the value part of the dictionary.
public class AutoDictionary : Dictionary
{
///
/// Retrieves or updates an item with the specified key. If the item does not exist on update,
/// it will be created. If the item does not exist on retrieval, the value specified for
/// will be returned.
///
/// The key of the item to retrieve or update.
/// The value returned on retrieval when the item with the specified key does not exist.
/// The item with the specified key if it exists in this collection; otherwise, defaultValue.
public TValue this[TKey key, TValue defaultValue = default(TValue)]
{
get
{
if (ContainsKey(key))
{
// we already contain an item with this key, so return the value accordingly
return base[key];
}
else
{
// we do not already contain an item with this key, so create a new value set to the
// specified default value and return that
base.Add(key, defaultValue);
return defaultValue;
}
}
set
{
// the .NET Framework Dictionary`2 implementation handles the "add or update" case
// automatically if a non-existent key is specified
base[key] = value;
}
}
}
}