title: Why does HttpContext.Response.Cookies["foo"] add a cookie?
body: <p>I have just spent half a day tracking down a bug due to the following behaviour: -</p>
  
  <p>Imagine that there is <strong>not</strong> a cookie called "foo" in either the Http request's or response's cookie collections.  The following code returns null</p>
  
  <pre><code>A) HttpContext.Current.Request.Cookies["foo"]
  </code></pre>
  
  <p>The following code creates a new cookie called "foo" (with path="/" and blank value), adds it to the response's cookie collection and returns that</p>
  
  <pre><code>B) HttpContext.Current.Response.Cookies["foo"]
  </code></pre>
  
  <p>So (B) has the side effect that any pre-existing cookie called "foo" is overwritten on the client's browser.</p>
  
  <p>This is not a bug.  Someone actually coded this deliberately. Here is the disassembly of the Get method (the Item[string name] indexer delegates to this method.</p>
  
  <pre><code>    public HttpCookie Get(String name) {
          HttpCookie cookie = (HttpCookie)BaseGet(name); 
  
          if (cookie == null &amp;&amp; _response != null) { 
              // response cookies are created on demand 
              cookie = new HttpCookie(name);
              AddCookie(cookie, true); 
              _response.OnCookieAdd(cookie);
          }
  
          return cookie; 
      }
  </code></pre>
  
  <p>Obviously the MSDN docs do not mention this behaviour (although some users have added comments at the bottom of the docs that describe this behaviour).</p>
  
  <p>My question is can someone explain to me the rational why the <code>HttpCookieCollection</code> class has this behaviour.</p>