I just tried to create this simple implementation:
class Test
{
private int abc = 0;
public class TestClass
{
private void changeABC()
{
abc = 123;
}
}
}
If I compile it, it will complain:
Cannot access a non-static member of outer type 'A.Test' via nested type 'B.Test.TestClass'
I dont like the solution of setting: static int abc = 0;
Is there any other solution for this?
A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed.
There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes. A class created within class and outside method.
Terminology: Nested classes are divided into two categories: non-static and static. Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class.
You are probably coming from a Java background where this code would work as expected.
In C#, nested types are static (in the parlance of Java), i.e. they are not bound to an instance of the parent class. This is why your code fails. You need to somehow pass an instance of the parent class to the child class and access its member abc
.
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