Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access variable of an Outer class in the inner class in c# [duplicate]

Tags:

c#

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

like image 543
Thorin Oakenshield Avatar asked Jun 29 '10 09:06

Thorin Oakenshield


2 Answers

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.

like image 69
Dr Herbie Avatar answered Sep 28 '22 14:09

Dr Herbie


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;
        }
    }
}
like image 34
Jason Down Avatar answered Sep 28 '22 14:09

Jason Down