Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested class - calling the nested class from the parent class

Tags:

c#

class

asp.net

I have a class whereby a method calls a nested class. I want to access the parent class properties from within the nested class.

public class ParentClass
{
    private x;
    private y;
    private z;

    something.something = new ChildClass();

    public class ChildClass
    {
        // need to get x, y and z;
    }
}

How do I access x,y and z from within the child class? Something to do with referencing the parent class, but how?

like image 422
insanepaul Avatar asked Mar 30 '10 23:03

insanepaul


1 Answers

Use the this keyword to pass a reference to 'yourself' to the constructor of the ChildClass.

public class ParentClass
{
    public X;
    public Y;
    public Z;

    // give the ChildClass instance a reference to this ParentClass instance
    ChildClass cc = new ChildClass(this);

    public class ChildClass
    {
        private ParentClass _pc;

        public ChildClass(ParentClass pc) {
            _pc = pc;
        }

        // need to get X, Y and Z;
        public void GetValues() {
            myX = _pc.X
            ...
        }
    }
}
like image 91
Byron Ross Avatar answered Sep 28 '22 16:09

Byron Ross