Possible Duplicate:
Nested type problem
Let’s say I have this code:
public class Tree
{
private readonly int nodeCapacity;
public int NodeCapacity { get { return nodeCapacity; } }
public Tree(int nodeCapacity)
{
this.nodeCapacity = nodeCapacity;
}
private class Node
{
object[] objects;
Node()
{
objects = new object[nodeCapacity];
}
}
}
This doesn’t compile and gives this error:
Cannot access a non-static member of outer type…
Is there a way to access that non-static member of outer type (from nested class) without passing the variable via constructor parameter nor using “static” keyword?
No, there is no way to access an instance variable of the outer class from within the nested class.
In C#, nested classes are completely separate instances, and have no direct relation to the outer class instance. You would need to pass a specific instance of
Treeinto theNodeconstructor.This way, when the
Treecreates it’s nodes, it can passthisto the constructor, and it will be read correctly. There is no real downside here, though. SinceNodehas private accessibility, onlyTreeinstances could ever construct an instance in any case.