Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant way of adding an item to a Dictionary<> safely?

People also ask

How does a dictionary work in c#?

A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.

How to store key value pair in c#?

To add key-value pair in C# Dictionary, firstly declare a Dictionary. IDictionary<int, string> d = new Dictionary<int, string>(); Now, add elements with KeyValuePair.

Which container type is used to store key value pairs in c#?

Hashtable represents a data structure that can store objects as key value pairs. You can search for a value in an instance of Hashtable class using the corresponding key.


Just use the indexer - it will overwrite if it's already there, but it doesn't have to be there first:

Dictionary<string, object> currentViews = new Dictionary<string, object>();
currentViews["Customers"] = "view1";
currentViews["Customers"] = "view2";
currentViews["Employees"] = "view1";
currentViews["Reports"] = "view1";

Basically use Add if the existence of the key indicates a bug (so you want it to throw) and the indexer otherwise. (It's a bit like the difference between casting and using as for reference conversions.)

If you're using C# 3 and you have a distinct set of keys, you can make this even neater:

var currentViews = new Dictionary<string, object>()
{
    { "Customers", "view2" },
    { "Employees", "view1" },
    { "Reports", "view1" },
};

That won't work in your case though, as collection initializers always use Add which will throw on the second Customers entry.


What's wrong with...

dict[key] = view;

It'll automatically add the key if it's non-existent.


simply

dict[key] = view;

From the MSDN documentation of Dictionary.Item

The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.

My emphasis


As usual John Skeet gets in there with lighting speed with the right answer, but interestingly you could also have written your SafeAdd as an Extension Method on IDictionary.

public static void SafeAdd(this IDictionary<K, T>. dict, K key, T value)...