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
}
}
}
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.
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.
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.
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.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With