I have written a small code, but found something amazing. I have a class name Students and inside that calss declared a List<> like this with variable name Students (same as the Class name)
Class Students
{
private String Name;
private int Age;
public Students(){}
List<Students> Students = new List<Students>();
...
}
Here compile time error is
‘Students’: member names can not be the same as their enclosing type
But if I declare the same List in other class … like
Class Students
{
private String Name;
private int Age;
public Students(){}
...
}
Class Program
{
....
List<Students> Students = new List<Students>();
Students.Add(new Students("Deb","B++"));
Students.Add(new Students("DDD", "A++"));
............
}
This Works fine.
My Question is, why? How we can create custom variable as the class name in other calsses but not in the same class?
Any elaborate answer would be good, as I want to gain knowledge in this.
The answer is mentioned in the error message:
It’s only an error if you are inside the class with the same name as the member.
Anyway, it’s a bad idea in any case to name variables like this. They should be not be capitalized.
Edit: Here’s an example that might cause ambiguity:
Edit 2: Searching around a bit I’ve found a very similar question: Why C# member names can't be the same as the enclosing type name? and the consensus was just that it’s a limitation of C# (no clear explanation why). VB.NET seems to allow that this situation to occur.