2

My code won't compile with this error:

Embedded statement cannot be a declaration or labeled statement

This doesn't compile:

for (int i = 0; i < 10; i++)            
    DateTime xs = DateTime.Now;

but this does:

for (int i = 0; i < 10; i++)
{
    DateTime xs = DateTime.Now;
}      

MSDN only explains the fact but not the reason why.

Byyo
  • 2,163
  • 4
  • 21
  • 35
  • 1
    A clear explanation can be found here: http://stackoverflow.com/questions/2496589/variable-declarations-following-if-statements – Liren Yeo Mar 18 '16 at 07:26
  • The MSDN page actually *does* explain it. "An embedded statement, such as the statements following an if statement, can contain neither declarations nor labeled statements." – Timothy Groote Mar 18 '16 at 07:28
  • @TimothyGroote that's the quote in my question but that doesn't explain the reason – Byyo Mar 18 '16 at 07:35

2 Answers2

4

It's because in the first instance you are declaring a variable that cannot be read. The scope of the variable is the single embedded statement. Therefore, declaring a variable in that statement is nonsensical.

In the second case, the variable's scope is a block, and other statements can be included in a block. The variable can therefore be used.

phoog
  • 42,068
  • 6
  • 79
  • 117
2

I believe it is because it is a single line only, you are declaring a variable scoped within a for loop (which is subject to not execute under certain conditions).

So basically it is using smarts to say that it is impossible for you to use this variable within 1 line, so you need to declare it outside the loop.

MikeDub
  • 5,143
  • 3
  • 27
  • 44
  • error prevention by forcing the user to declare it outside the loop +1 – Byyo Mar 18 '16 at 07:31
  • The fact that the line might not execute is not really important. For example, it's not an error to declare variables inside an `if (false) { }` block. @Byyo how would forcing the user to declare it outside the loop prevent an error? – phoog Mar 18 '16 at 09:23