title: Reading cookie in c#
body: <p>I want someone who visits my internationalized site to be able to change the language. I thought best way would be to store the language chosen in a cookie - so when the page loads, it can look up the preferred language in the cookie.</p>
  
  <p>Writing the cookie is going perfect, however I keep running into errors trying to read it.
  As I'm new to C# im having trouble translating the errors visual studio throws at me.</p>
  
  <p>I want the value of a cookie called 'UserSettings' in a string called lang. I'm trying like this:</p>
  
  <pre><code>string lang = Request.Cookies["UserSettings"].Value;
  </code></pre>
  
  <p>The error it throws is:</p>
  
  <blockquote>
    <p>Object reference not set to an instance of an object</p>
  </blockquote>
  
  <p>I'm thinking the problem has to be on the right side of the statement, since I'm initializing the string on the left side.</p>
  
  <p>I also tried making an instance of the cookie by doing  </p>
  
  <pre><code>HttpCookie cookie = Request.Cookies["UserSettings"].Value;
  </code></pre>
  
  <p>but visual studio doesnt like this at all.</p>
  
  <p>What am I doing wrong? Do I have to make an instance of the Request object? Any help would be appreciated.</p>
  
  <p>I'm following different tutorials on this topic, but they all result in this same error.</p>
  
  <p><strong>EDIT:</strong> I've noticed I had    </p>
  
  <pre><code>HttpCookie cookie = Request.Cookies["UserSettings"].Value;
  </code></pre>
  
  <p>I changed it to:  </p>
  
  <pre><code>HttpCookie cookie = Request.Cookies["UserSettings"]; 
  </code></pre>
  
  <p>but no luck, it still didn't work.</p>
  
  <p><strong>EDIT:</strong> this is how my cookie is made</p>
  
  <pre><code> public void Application_BeginRequest()
      {
          myCookie = new HttpCookie("UserSettings");
          myCookie.Value = "nl";
          myCookie.Expires = DateTime.Now.AddDays(1);
          Response.Cookies.Add(myCookie);
          hc = new HomeController();
      }
  </code></pre>
  
  <p>My cookie is 100% there, im absolutly sure, i can see it in Firefox-web developer.</p>
  
  <p>UPDATE: this is the exact code i'm calling now</p>
  
  <pre><code>        public string getLang()
      {
         // HttpCookie aCookie = Request.Cookies["UserSettings"];
         //  string lang = Server.HtmlEncode(aCookie.Value);
         //  if (lang != null)
         // {
         //      currentLanguage = lang;
         //  }
          return currentLanguage;
      }
  </code></pre>
  
  <p>this way my code compiles, if I uncomment my code then it doest (error @ first line of this method)</p>