Reputation: 5281
In C#, why does a nested class have to instantiate it's parent class, to reference its parent class non-static properties in code?
public class OuterClass
{
public int OuterClassProperty
{
get
{
return 1;
}
}
public class InnerClass
{
public int InnerClassProperty
{
get
{
/* syntax error: cannot access a non-static
* member of outer type via nested type.
*/
return OuterClassProperty;
}
}
}
}
It seems I have to do this instead:
public class OuterClass
{
public int OuterClassProperty
{
get
{
return 1;
}
}
public class InnerClass
{
public int InnerClassProperty
{
get
{
OuterClass ImplementedOuterClass = new OuterClass();
return ImplementedOuterClass.OuterClassProperty;
}
}
}
}
I'm thinking the first code example should be okay, because if InnerClass
is instantiated, the parent class would implemented first - along with the parent class properties.
Thanks for the help, I'm trying to learn the in's and out's of C#... and I am not familiar with Java, comparing to Java won't help much...
Upvotes: 2
Views: 1729
Reputation: 100547
The behavior you are observing is explicitly spelled out in the C# specification. Snippet of C# 5.0 below:
10.3.8.4 this access
A nested type and its containing type do not have a special relationship with regard to this-access (§7.6.7). Specifically, this within a nested type cannot be used to refer to instance members of the containing type. In cases where a nested type needs access to the instance members of its containing type, access can be provided by providing the this for the instance of the containing type as a constructor argument for the nested type.
The behavior of nested classes in C# is different for other language like Java inner classes in c# and C+ because C# is different language created by different language design team. Exact historical reasons why particular behavior was selected possibly could be found in blogs of members of C# design team, .Net design guidelines book or MSDN articles.
Upvotes: 5