title: C# multithreaded code access to local variables inside a lock
body: <p>My question has to do with the following bit of code. I simplified the code to distill the question. </p>
  
  <p>I understand that the lock keeps the foo Hashtable variable from being changed, but what about the variable outside the lock? We're seeing some odd behavior in code that looks like this and this was the question that came up. Thanks for any input.</p>
  
  <pre><code>using System.Collections;
  
  namespace MultithreadScratch01
  {
      public class ThreadFoo
      {
          public void Foo(Stub2 stub2, Hashtable foo)
          {
              Stub1 bar;
  
              var prop1 = stub2.Prop1;
              var prop2 = stub2.Prop2;
              var prop3 = stub2.Prop3;
  
              var hash = string.Format("{0}_{1}_{2}", prop1, prop2, prop3);
  
              lock(foo)
              {
                  if(!foo.Contains(hash))
                  {
                      bar = new Stub1 {Foo = "some arbitrary string", Bar = 123};
                      foo.Add(hash, bar);
                  }
              }
  
          }
          public class Stub1
          {
              public string Foo { get; set; }
              public int Bar { get; set; }
          }
          public class Stub2
          {
              public string Prop1 { get; set; }
              public string Prop2 { get; set; }
              public string Prop3 { get; set; }
  
          }
      }
  }
  </code></pre>