views:

754

answers:

2

Currently I'm using

var x = dict.ContainsKey(key) ? dict[key] : defaultValue

I'd like some way to have dictionary[key] return null for nonexistant keys, so I could write something like

var x =  dict[key] ?? defaultValue;

this also winds up being part of linq queries etc. so I'd prefer one-line solutions.

+4  A: 

You can use a helper method:

public abstract class MyHelper {
    public static V GetValueOrDefault<K,V>( Dictionary<K,V> dic, K key ) {
        V ret;
        bool found = dic.TryGetValue( key, out ret );
        if ( found ) { return ret; }
        return default(V);
    }
}

var x = MyHelper.GetValueOrDefault( dic, key );
TcKs
You can also trivially make that an extension method, so you can do dict.GetValueOrDefault( key )
stevemegson
I thought he did that in the first place... Odd that the only difference would be the 'this' keyword.
Will
You can actually make this unconditional - just return ret after the call to TryGetValue. It will default(V) if the method returns false.
Jon Skeet
@Jon - good point.. however, I would advocate making this an extension method on the interface `IDictionary<K,V>` rather than `Dictionary<K,V>` and some weird (semantically wrong) implementation might return something other than default(V)
AdamRalph
+5  A: 

With an extension method:

public static class MyHelper
{
    public static V GetValueOrDefault<K, V>(this Dictionary<K, V> dic, K key, V defaultVal)
    {
        V ret;
        bool found = dic.TryGetValue(key, out ret);
        if (found) { return ret; }
        return defaultVal;
    }
    void Example()
    {
        var dict = new Dictionary<int, string>();
        dict.GetValueOrDefault(42, "default");
    }
}
Brian
I'd offer an overload that returns default(V)
Will