onsdag 29 juni 2011

Tiplet #1: Extension to make dictionary lookups less clunky

For TValues that are of reference type, looking up values can be made less clunky by the following extension method:

public static TValue TryGetValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
        where TValue : class
{
        TValue val;
        dictionary.TryGetValue(key, out val);
        return val;
}

The return value will be null if the key doesn't exist. This will also be the case if there is a key with a null value, but often you don't care about the distinction.

Since the hateful "out" is gone, you can now use the method directly in expressions.

Value val = dictionary.TryGetValue(key);
return dictionary.TryGetValue(key);
other.Foo = replacementFoos.TryGetValue(fooKey) ?? other.Foo;


Inga kommentarer:

Skicka en kommentar