Pergunta

We wanted to assign/add an item to a Dictionary using the key index, like this:

Dictionary<string, object> dict = new Dictionary<string, object>();
dict["key"] = dict["key"] ?? "object";

But it results to: "The given key was not present in the dictionary."

Is there any way we could assign values to this dictionary the same as the way I assign values to sessions, using null coalesce:

Session["Member"] = Session["Member"] ?? new Member();

Thanks

Edit: I actually tried to override the indexer from a child class of dictionary, but to no avail. Implementing IDictionary interface would seem too much because we just need the functionality of the code below (i.e., return null if key is not found). So I think, maybe we could use extensions like:

public static TValue [this Dictionary<TKey, TValue> thisDictionary, TKey key] {
    get { return thisDictionary.ContainsKey(key) ? thisDictionary[key] : null; }
    set { thisDictionary[key] = value; }
}

but it is not working or even compiling.

Any other simpler ways so we could reuse this indexer functionality? Thanks a lot.

Foi útil?

Solução

If you want to do this inline:

dict["key"] = dict.ContainsKey("key") ? (dict["key"] ?? "object") : "object"; 

Alternatively:

dict["key"] = dict.ContainsKey("key") && dict["key"] == null ? dict["key"] : "object";

Edit as per comments:

public static TValue GetSafe(this Dictionary<TKey, TValue> thisDictionary, TKey key) 
{ 
   if (!thisDictionary.ContainsKey(key))
       thisDictionary[key] = null;

   return thisDictionary[key];
}

This allows you to do this:

thisDictionary["randomKey"] = thisDictionary.GetSafe("randomKey") ?? "someValue";

Outras dicas

As you noted, trying to fetch a missing key throws an exception. You have to check if the key exists first:

if( !Session.ContainsKey("Member") )
    Session["Member"] = new Member();

Edit:

And to answer your question; you can create your own indexer or implement the IDictionary interface. This way you can avoid the default behavior of throwing an exception

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top