.NET C# Extension Methods - IDictionary

Thursday, November 19, 2009

.NET C# Extension Methods - IDictionary

Other extension methods:

---------------------------

Extension method for IDictionary. Returns the values associated with the key specified by parameter key.

        /// <summary>
/// Gets the value of an element within a dictionary object.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="bag">The actual dictionary.</param>
/// <param name="key">The key that will be searched for within the dictionary object.</param>
/// <param name="defaultValue">Returns default value if the specified key was not found.</param>
/// <returns>Specific value within dictionary object.</returns>
public static TValue GetValue<TValue>( this IDictionary bag, string key, TValue defaultValue )
{
object value = bag[ key ];

if( value == null )
{
value = defaultValue;
}

return defaultValue;
}

Extension method for IDictionary. Adds a key-value pair.

        /// <summary>
/// Adds a (key,value) pair in a dictionary object.
/// </summary>
/// <typeparam name="TKey">The type of keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values in the dictionary.</typeparam>
/// <param name="bag">The actual dictionary.</param>
/// <param name="key">The name of the key used for easy navigation in a dictionary object.</param>
/// <param name="value">The value assoiciated with the key.</param>
public static void SetValue<TKey, TValue>( this IDictionary<TKey,TValue> bag, TKey key, TValue value )
{
if( bag.ContainsKey( key ) )
{
bag[ key ] = value;
}
else
{
bag.Add( key, value );
}
}

No comments:

Post a Comment