What's the best way of accessing field in the enclosing class from the nested class?
Solution 1:
Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference. Raymond Chen has an example describing the differences here : C# nested classes are like C++ nested classes, not Java inner classes.
Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference.
// C#
class OuterClass
{
string s;
// ...
class InnerClass
{
OuterClass o_;
public InnerClass(OuterClass o) { o_ = o; }
public string GetOuterString() { return o_.s; }
}
void SomeFunction() {
InnerClass i = new InnerClass(this);
i.GetOuterString();
}
}
Note that the InnerClass can access the "s
" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the "string s;
" is private
because no other access permission was specified.
Solution 2:
Nested types aren't like inner classes in Java - there's no inherent instance of the containing type. (They're more like static nested classes in Java.) They're effectively separate classes, with two distinctions:
- If the containing type is generic, the nested type is effectively parameterised by the containing type, e.g.
Outer<int>.Nested
isn't the same asOuter<string>.Nested
. - Nested types have access to private members in the containing type.