Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested class: Cannot access non-static field in static context

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
        }
    }
}
like image 595
Sisiutl Avatar asked Jun 11 '12 23:06

Sisiutl


People also ask

Can static context access non-static content?

Of course, they can, but the opposite is not true, i.e. you cannot obtain a non-static member from a static context, i.e. static method. The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs to.

Can static method access non-static field?

A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables. Also, a static method can rewrite the values of any static data member.

Can we access from non-static nested classes?

1 Answer. The explanation is: The non-static nested class can access all the members of the enclosing class. All the data members and member functions can be accessed from the nested class. Even if the members are private, they can be accessed.

What all are members can be accessed from static nested class?

Therefore, the answer becomes intuitive: a static nested class can access all members of an enclosing class that can be accessed without an instance of that class.


1 Answers

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
        }
    }
}
like image 192
Ben Voigt Avatar answered Oct 21 '22 12:10

Ben Voigt