Method Definition Naming Conflict

Inside a method, there can be only one object of any name. We avoided reusing the same variable names using the block level however, in an earlier example, however, an object with the same name outside the block area will show why this does not work. See This Example Demonstrating this Name Conflict:

public static void DoWork()
{
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(i);
    }
    int i = 777; // Compiler error here
    Console.WriteLine(i);
}

Above from https://www.microsoft.com/net/tutorials/csharp/getting-started/scope-accessibility , I want to ask why this will happen? Why is C # created this way since C ++ and Java have nothing like this (I tested, there are no restrictions in Java and C ++)

+4
source share
2 answers

,

, / , , .

, , , , .

+6

, , 100% .

,

public static void DoWork()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(i);
        }
        { 
          // adding this block will remove the compiler error, 
          // and yes you can use the same variable name in the same 
          // method but you need to help the compiler that each 
          // variable usuage is under its own block.
            int i = 777; // Not compiler error anymore
            Console.WriteLine(i);
        }
    }

, , ,

,

0

Source: https://habr.com/ru/post/1654961/


All Articles