title: Is there a more elegant way of adding an item to a Dictionary<> safely?
body: <p>I need to add key/object pairs to a dictionary, but I of course need to first check if the key already exists otherwise I get a "<strong>key already exists in dictionary</strong>" error. The code below solves this but is clunky.</p>
  
  <p><strong>What is a more elegant way of doing this without making a string helper method like this?</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  
  namespace TestDictStringObject
  {
      class Program
      {
          static void Main(string[] args)
          {
              Dictionary&lt;string, object&gt; currentViews = new Dictionary&lt;string, object&gt;();
  
              StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1");
              StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2");
              StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1");
              StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1");
  
              foreach (KeyValuePair&lt;string, object&gt; pair in currentViews)
              {
                  Console.WriteLine("{0} {1}", pair.Key, pair.Value);
              }
              Console.ReadLine();
          }
      }
  
      public static class StringHelpers
      {
          public static void SafeDictionaryAdd(Dictionary&lt;string, object&gt; dict, string key, object view)
          {
              if (!dict.ContainsKey(key))
              {
                  dict.Add(key, view);
              }
              else
              {
                  dict[key] = view;
              }
          }
      }
  }
  </code></pre>