Alex Rivera | Logout

Using a variable name used in a child scope

Asked 2010-01-13T18:29:29.917
14

I've been wondering why in C# using a variable name used previously in a child scope is not allowed. Like this:

if (true)
{
    int i = 1;
}

int i = 2;

Compiling the above code produces an error:

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

And yet you can't use the variable defined in child scope either. The code above works just fine in Java and I can see no reason why it doesn't in C# too. I'm sure there's a good reason, but what is it?

c#
Edit
Report

1 Answer

1

As Adam Crossland said, it's a design choice - Made to make sure you (or more likely, your fellow developers) dont misunderstand the code.

You often see private instance members prefixed with a "m_" or "_" (eg. _myVar or m_myVar) to avoid confusion..

answered 2010-01-13T18:38:16.697

Your Answer