How to access to the Outer class's field from Inner class of same name in C#? (nested-class)

StackOverflow https://stackoverflow.com/questions/19480793

  •  01-07-2022
  •  | 
  •  

Question

How can I access to the field of outer class from inner class if the name of parameter is same as the outer class's field name?

For example -

class OuterClass
{
    static int Number;

    class InnerClass
    {
        public InnerClass(int Number)
        {
            Number = Number;   // This is not correct
        }
    }
}

So I tried like below -

class OuterClass
{
    static int Number;

    class InnerClass
    {
        public InnerClass(int Number)
        {
            this.this.Number = Number;   // Gives compiler error
        }
    }
}

How can I access it, please help ...

Thanks.

Was it helpful?

Solution

you are looking for

class OuterClass
{
    static int Number;

    class InnerClass
    {
        public InnerClass(int Number)
        {
            OuterClass.Number = Number;   
        }
    }
}

OTHER TIPS

Since it is static, you can just access it by writing: OuterClass.Number = Number;

You can do something in the lines of this:

Public InnerClass
{
    private MainClass _mainclass;

    public InnerClass(MainClass mainclass)
    {
         this._mainclass = mainclass;
    }


}

This way, you always create the inner class with a reference to the parent class and can call it with mainclass.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top