4
Answers

Local variable cannot be declared because it would give a different meaning to the variable in a 'child' scope... Huh?

Jitse

Jitse

17y
10.3k
1
Hi ho,

I've encountered a weird thing with C#. Apparently when you do something like this:

private void MyMethod()
{
  for (int i = 0; i < 10; i++)
  {
  }
 
  int i = 5; // this gives an error...
}

This is just extremely weird and annoying. According to MS this is to protect the programmer, for example when he copy/paste a piece of code. But that's just ridiculous, a variable declared in the scope of the for loop should stay there, and get disposed when the loop ends. And even weirder is that you can still do this:

private void MyMethod()
{
  for (int i = 0; i < 10; i++)
  {
  }
 
  for (int i = 0; i < 10; i++) // shouldn't this give an error then? no it doesn't, don't ask me why...
  {
  }
}

Why does this compile then? If MS wants i to have the scope of the whole method, why am I still able then to declare it in a second for loop, but not in a normal way?

Thanks in advance,
Jitse
Answers (4)