title: Why can a local variable be accessed in another thread created in the same class?
body: <p>I couldn't really find anything on this exact topic, so please lead me toward the right direction, if a question already exists.</p>
  
  <p>From what I have learned about .NET, it is not possible to access variables across different threads (please correct me if that statement is wrong, it's just what I have read somewhere).</p>
  
  <p>Now in this codesample, however, it then seems that it shouldn't work:</p>
  
  <pre><code>class MyClass
  {
      public int variable;
  
      internal MyClass()
      {
          Thread thread = new Thread(new ThreadStart(DoSomething));
          thread.IsBackground = true;
          thread.Start();
      }
  
      public void DoSomething()
      {
          variable = 0;
          for (int i = 0; i &lt; 10; i++)
              variable++;
  
          MessageBox.Show(variable.ToString());
      }
  }
  
  public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
      }
  
      private void SomeMethod();
      {
          MyClass mc = new MyClass();
      }
  }
  </code></pre>
  
  <p>When I run <code>SomeMethod()</code> shouldn't .NET throw an exception, because the created object <code>mc</code> is running in a different thread than the thread created within the <code>mc</code>-initializer and this new thread is trying to access the local variable of <code>mc</code>?</p>
  
  <p>The <code>MessageBox</code> shows <code>10</code> as (not) expected, but I am not sure why this should work.</p>
  
  <p>Maybe I didn't know what to search for, but no threading-topic I could find, would address this issue, but maybe my idea of variables and threads is wrong.</p>