12

I have a class C with some internal variables. It has a nested class N that wants to access the variables in C. Neither C nor N are static, although C has some static methods and variables. When I try to access a non-static variable in C from N I get the squiggly underline and the message "Cannot access non-static field [fieldname] in static context".

This seems to have something to do with the nested class, since I can access the variable fine from the enclosing class itself.

ReSharper suggests I make _t static but that isn't an option. How do I deal with this?

public sealed partial class C
{
    string _t;

    class N
    {
        void m()
        {
            _t = "fie"; // Error occurs here
        }
    }
}
Sisiutl
  • 4,915
  • 8
  • 41
  • 54
  • 2
    possible duplicate of [Inner class and Outer class in c#](http://stackoverflow.com/questions/3155172/inner-class-and-outer-class-in-c-sharp) and http://stackoverflow.com/questions/2367015/java-inner-classes-in-c-sharp – Ben Voigt Jun 11 '12 at 23:51

1 Answers1

15

This isn't Java, and you don't have inner classes.

An instance of a nested class is not associated with any instance of the outer class, unless you make an association by storing a reference (aka handle/pointer) inside the constructor.

public sealed partial class C
{
    string _t;

    class N
    {
        readonly C outer;

        public N(C parent) { outer = parent; }

        void m()
        {
            outer._t = "fie"; // Error is gone
        }
    }
}
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 2
    The O'Reilly "Nutshell" book (Albahari & Albahari) says "A nested type ... can access the enclosing type's private members and everything else the enclosing type can access." – Sisiutl Jun 11 '12 at 23:56
  • 1
    @Sisiutl: This has nothing to do with accessibility. Because of the rule "Nutshell" mentions, my code works even with `private string _t;`. Without that rule, you would need either `internal` or `public`. A static method also has access to private members, but needs to supply an instance reference before using non-static members. – Ben Voigt Jun 11 '12 at 23:59