title: C# MemoryCache for 2 different types of keys?
body: <p>I am using <code>MemoryCache</code> to store key/value pairs in my MVC .Net application.</p>
  
  <p>There are 2 main purposes I am using <code>MemoryCache</code>. One is to store sessions for user ids, and another is to store constants (this is just an example) The keys could theoretically be the same in both cases, so I want some way to separate these 2.</p>
  
  <p>I am thinking of 2 or 3 ways. Which way is superior? Or is there a better alternative?</p>
  
  <ol>
  <li><p><strong>Each key in the cache will be prepended by a namespace.</strong></p>
  
  <blockquote>
    <p>"user_session:1", "user_session:2"<br>
    "constants:1", "constants:2"</p>
  </blockquote></li>
  <li><p><strong>Using nested dictionaries as keys.</strong></p>
  
  <blockquote>
    <p>There will be a key "user_sessions" whose value will be a Dictionary that maps ids to the session object. There will be a key "constants" whose value will be a Dictionary.</p>
  </blockquote></li>
  <li><p><strong>Each "namespace" gets its own MemoryCache instance.</strong></p></li>
  </ol>
  
  <p>The disadvantage with #2 is that when I want to get the value belonging to a user ID, I need to first get the dictionary, then get the value for a key in that dictionary. Which means I need to store the dictionary in memory.</p>
  
  <p>IE: </p>
  
  <pre><code>Dictionary&lt;string, string&gt; userSessions = MemoryCache.Default["user_sessions"]
  object session = userSessions.get("1");
  </code></pre>