How to access Outer class variable in inner class in C #

I have two classes, I have to declare a variable common to both classes.

In the case of nested classes, I need to access the Outer class variable in the inner class

please give me the best way to do this in C #.

Code example

 Class A
   {
     int a;
     Class B
        {
               // Need to access " a" here
        }
    }

Thanks in advance

+3
source share
3 answers

The first sentence is to pass a reference to the Outer class to the Inner class when building, so the Inner class, which refers to the properties of the Outer class.

+9
source
public Class Class_A
{
    int a;

    public Class Class_B
    {
        Class_A instance;

        public Class_B(Class_A a_instance)
        {
            instance = a_instance;
        }

        void SomeMethod()
        {
            int someNumber = this.instance.a;
        }
    }
}
+4
source

In your example, you probably need to pass a as parameter B to the constructor - there is no way to access it otherwise. However, having it as a β€œchild” class may not be a great design, but there is not enough information to really know anyway.

0
source

Source: https://habr.com/ru/post/1752244/


All Articles