Possible Duplicate:
Why can't a duplicate variable name be declared in a nested local scope?
I am new to C# and recently noticed that scoped objects in C# when declared within two different scopes can't have the same name as in Java. Why is this design limitation placed? Any ideas? E.g. the following code will not work in C#,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
private string Name = "";
public Program(string Name)
{
this.Name = Name;
}
public static void Main(string[] args)
{
bool flag = true;
if (flag)
{
Program p = new Program("");
return;
}
Program p = new Program("");
return;
}
}
}
The 24th line of the code where the second instance of class Program is created in terms of reference p creates a compile time error. Whereas the exact same code runs in Java without any problem,
public final class Test {
private String Name = "";
public Test (String Name) {
this.Name = Name;
}
public static void main(String[] args) {
boolean flag = true;
if (flag)
{
Test t = new Test("");
return;
}
Test t = new Test("");
return;
}
}
If I remember from my compiler class: as the control flow of the inner nested scope (within the if loop) is independent of the part of the main below it, there is no harm at all in allowing the user to use the same variable name reference (as done by the Java compiler). It should not be a compile time error. So is there a mystery in C# having such a design restriction?