Why is this code giving a compile error?

Hi,

I tried to compile a class containing only the following method but it gives the error
"Error 1 A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else".
Why is it so

Please help..

public static void M()

{

   {

      char i = 'a';

   }

   int i = 0;

}



Answer this question

Why is this code giving a compile error?

  • Barry Bond

    Coming from C++, this rule really irritates me. What is especially annoying is that it doesn't even let you declare a variable in an outer scope AFTER one of the same name has been declared in an inner scope, even though that could not possibly conflict. Consider:


    if ( something )
    {
        int i = 10; //A
        Console.WriteLine( i );
    }

    int i = 10;  //B

     


    The compiler error given for the line marked B says:
    A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else

    Well, duh! No it won't! A variable is in scope from its point of declaration, so the 'i' introduced at B will NOT give a different meaning to the one introduced at A.

    Grrrr!

  • johndog

    In c# it is not allowed to declare a variable wih same name in a function ,ie a variable is not allowed to shadow another variable with same name.Which on other hand is allowed in c++.Also if u declare one variable as of Field level  and another with function level having same name this would work.Smile

  • Meryl Junik

    ironically, not possible.

  • Olivier Georg

     "i" is declared in the outer block and cannot be redeclared in the inner block. In this case C# behave like if "i" is a method: The method scope is the block in with you declarate it, do you can call to a method "b" from the method "a" declarated before.

    You can found the theory in http://msdn.microsoft.com/library/default.asp url=/library/en-us/csspec/html/vclrfcsharpspec_3_3.asp

  • Luis Forero

    Hi,

    you declared a variable twice. If you made the first in a if or for statement it should work.

  • James Liddell

  • Tanvir

    Ironically however, i belief (from memory) that this -is- possible:




    class
    ="txt4" id="_ctl0_MainContent__ctl0_PostForm_ReplyBody"> int i = 20;  //B

    if ( something )
    {
        int i = 10; //A
        Console.WriteLine( i ); // 10
    }

    Console.WriteLine( i ); // 20


     


  • Why is this code giving a compile error?