1

Possible Duplicate:
C# Variable Scoping

Consider this code:

void f()
{
  if (condition) 
  {
     B b = createB();
  }
  ...
  B b = getB();
}

I get an error complaining about variable b already defined in child scope. Why is this? The first definition occurs in nested scope which is not visible to outer scope. I can't even access the previously declared variable in outer scope. So what is the compiler doing in this case?

Community
  • 1
  • 1
user236215
  • 7,278
  • 23
  • 59
  • 87
  • Because you define the variable twice? If the condition is true, then the the variable is defined twice, otherwise its not. – Security Hound Nov 03 '12 at 16:44

2 Answers2

0

Try this piece of code instead and compiler won't complain:

void f()
{
  B b = null;
  if (condition) 
  {
     b = createB();
  }
  ...
  b = getB();
}
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
  • I know but what is the basis of compiler decision in my case. I dont want to predeclare everything outside – user236215 Nov 03 '12 at 16:00
  • Theoretically is should be acceptable but still invalid as far as C# is concerned. Primarily because B is a reference type and it doesn't destroy out of if scope instead when GC execute. – Furqan Safdar Nov 03 '12 at 16:08
  • @user236215 - Why? The code your asking about is BAD programming. – Security Hound Nov 03 '12 at 16:44
0

It accounts for the possibility of it being created twice. Initialize the variable in your first line, then set the values where you are creating it now. This means it will only be created once, but will carry the same values you would have if this worked.

Edit: see FSX's answer for the code... this is just an explanation of why it happens.

Matt Olan
  • 1,911
  • 1
  • 18
  • 27