Home > front end >  Access member variables from the MainClass inside a class defined in MainClass?
Access member variables from the MainClass inside a class defined in MainClass?

Time:01-06

I want to access the member variables inside a class MainClass, from inside a class defined in that MainClass. Can i do that?

public class MainClass
{
    public int x = 1;

    public class Class1
    {
        public void class1Function()
        {
            this.x = 4; //somehow access the x of instance of MainClass
        }
    }

    public static class Class2
    {
        public static void class2Function()
        {
            this.x = 5; //also can i do this from a static function?
        }

    }

    public void mainFunction()
    {
        System.Console.WriteLine(this.x); //this works just fine, obviously
    }
}

CodePudding user response:

Class1 and Class2 cannot access x from MainClass because an instance of a nested class isn't associated with an instance of the outer class. (Corrected based on Joe Sewell's hint)

You could inherit MainClass like this: public class Class1 : MainClass. Then you can access this.x.

Accessing a mutable variable from a static context, which is the case for Class2 is not possible. If you want to use x in class2Function you could pass it and return the modified version that you need (Closure of Operations).

  • Related