title: Is a lock possible per instance of an object?
body: <p>I have understood that <code>lock()</code> locks a region of lines of code, other threads cannot access the locked line(s) of code. EDIT: this turns out to be just wrong.<br>
  Is it also possible to do that <em>per instance</em> of an object? EDIT: yes, that's is just the difference between static and non-static.   </p>
  
  <p>E.g. a <code>null</code> reference is checked during a lazy load, but in fact there is no need to lock other objects of the same type?</p>
  
  <pre><code>object LockObject = new object();
  List&lt;Car&gt; cars;
  public void Method()
  {
     if (cars == null)
     {
        cars = Lookup(..)
        foreach (car in cars.ToList())
        {
            if (car.IsBroken())
            {
               lock(LockObject)
                {
                   cars.Remove(car)
                }
             }
         }
      }
      return cars;
  }
  </code></pre>
  
  <p>EDIT, would this be a correct way to write this code:<br>
  Because when <code>cars == null</code> and thread A locks it, then another thread B will wait. Then when A is ready, B continues, but should check again whether <code>cars == null</code>, otherwise the code will execute again.<br>
  But this looks unnatural, I never saw such a pattern.<br>
  Note that locking the first <code>null</code>-check would mean that you acquire a lock even to check for <code>null</code> and every time again and again .. so that is not good.</p>
  
  <pre><code>public void Method()
  {
     if (cars == null)
     {
        lock(LockObject)
        {
           if (cars == null)
           {
              cars = Lookup(..)
              foreach (car in cars.ToList())
               {
                 if (car.IsBroken())
                 {
                     cars.Remove(car)
                 }
               }
            }
         }
      }
      return cars;
  }
  </code></pre>