Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# local variable scope [duplicate]

Tags:

c#

Possible Duplicate:
confused with the scope in c#

It appears that in C# a variable defined with the local scope to if/else/loop block is conflicting with variable defined outside following that block - see code snipped. An equivalent code compiles fine under C/C++ and Java. Is this expected behavior in C#?

public void f(){
  if (true) {
    /* local if scope */
    int a = 1;
    System.Console.WriteLine(a);
  } else {
    /* does not conflict with local from the same if/else */
    int a = 2;
    System.Console.WriteLine(a);
  }

  if (true) {
    /* does not conflict with local from the different if */
    int a = 3;
    System.Console.WriteLine(a);
  }

  /* doing this:
   * int a = 5;
   * results in: Error 1 A local variable named 'a' cannot be declared in this scope
   *  because it would give a different meaning to 'a', which is already used in a 
   *  'child' scope to denote something else
   * Which suggests (IMHO incorrectly) that variable 'a' is visible in this scope
   */

  /* doing this: 
   * System.Console.WriteLine(a);
   * results in: Error 1 The name 'a' does not exist in the current context..
   * Which correctly indicates that variable 'a' is not visible in this scope
   */
}
like image 446
luchon Avatar asked Aug 21 '12 18:08

luchon


2 Answers

Yes, this is how C# works.

When declaring a scope, any local variable from an outer scope is also known - there is no way to qualify that a local variable within the scope should override the local variable from outside.

like image 66
Oded Avatar answered Sep 28 '22 17:09

Oded


It looks like you are concerned with the order of declaration (redeclaring a after the if blocks).

Consider the case that it is declared before the if blocks. Then you would expect it to be available within the scope of those blocks.

int a = 1;

if(true)
{
  var b = a + 1; // accessing a from outer scope
  int a = 2; // conflicts
}

There is not really a concept of "not in scope yet" at compile time.

You can actually create an inner scope with just bare curly braces:

{
   int a = 1;
}

if(true)
{
   int a = 2; // works because the a above is not accessible in this scope
}
like image 44
Jay Avatar answered Sep 28 '22 19:09

Jay