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.