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
  •  | 
  •  

Pregunta

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.

¿Fue útil?

Solución

you are looking for

class OuterClass
{
    static int Number;

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top