Wilsonhut

Deal with it or don't

Obvious Methods: IDictionary Get – With Defaults plus

This is a follow-up to my post Obvious Methods: IDictionary Get – with defaults

Now the methods will add to the list, if you want.

public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary,
		                                    TKey key, Func<TKey, TValue> getDefaultValue,
		                                    bool addDefaultToSource = false)
{
	TValue value;
	if (dictionary.TryGetValue(key, out value))
	{
		return value;
	}

	value = getDefaultValue(key);
	if (addDefaultToSource)
	{
		dictionary.Add(key, value);
	}
	return value;
}

public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key,
		                                    Func<TValue> getDefaultValue, bool addDefaultToSource = false) { return dictionary.Get(key, k => getDefaultValue(), addDefaultToSource); } public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue, bool addDefaultToSource = false) { return dictionary.Get(key, k => defaultValue, addDefaultToSource); } public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, bool addDefaultToSource = false) { return dictionary.Get(key, k => default(TValue), addDefaultToSource); }

Check out Obvious Methods: IDictionary Get – with defaults for how to use it.

Advertisements

One response to “Obvious Methods: IDictionary Get – With Defaults plus

  1. Pingback: Obvious Methods: IDictionary Get – with defaults | Wilsonhut

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: