title: Why can't we define a variable inside an if statement?
body: <p>Maybe this question has been answered before, but the word <code>if</code> occurs so often it's hard to find it.</p>
  
  <p>The example doesn't make sense (the expression is always true), but it illustrates my question.</p>
  
  <p>Why is this code valid:</p>
  
  <pre><code>StringBuilder sb;
  if ((sb = new StringBuilder("test")) != null) {
      Console.WriteLine(sb);
  }
  </code></pre>
  
  <p>But this code isn't:</p>
  
  <pre><code>if ((StringBuilder sb = new StringBuilder("test")) != null) {
      Console.WriteLine(sb);
  }
  </code></pre>
  
  <p>I found a similar question regarding a <code>while</code> statement. The accepted answer there says that in a <code>while</code> statement, it would mean the variable would be defined in each loop. But for my <code>if</code> statement example, that isn't the case.</p>
  
  <p>So what's the reason we are not allowed to do this?</p>