6

i have two class i need to declare a variable common to both the classes..

In case of Nested classes i need to access the Outer class variable in the inner class

please give me a better way to do this in c#.

Sample code

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

Thanks in advance

Thorin Oakenshield
  • 14,232
  • 33
  • 106
  • 146

3 Answers3

11

First suggestion is to pass a reference to the Outer class to the Inner class on construction, so Inner class that then reference Outer class properties.

Dr Herbie
  • 3,930
  • 1
  • 25
  • 28
5
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;
        }
    }
}
Jason Down
  • 21,731
  • 12
  • 83
  • 117
0

From your example, you probably need to pass a as a parameter to B in it's constructor - there's not way to access it otherwise. Having this as a 'child' class may not be a great design, however, but there's not enough information to really know either way.

Paddy
  • 33,309
  • 15
  • 79
  • 114