What’s the best way of accessing field in the enclosing class from the nested class?

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.

Leave a Comment