Don chan
Don chan

Reputation: 35

Is it possible to get known something about the class that contain object of another class, only from this object?

I have a class, let's say A. And have an another class,let's say B. Inside of A class I'm creating an object of B class, for example b. So is it possible somehow to get known about A class, if I get only b (object of B class) ? Like can i get known where b was created? Cause i want to work with A class.

Upvotes: 0

Views: 34

Answers (1)

John Wu
John Wu

Reputation: 52280

There is nothing built-in that lets you get a reference to the instance of A that created the instance of B. But you can do it yourself with a little code by passing this to B in the constructor.

class A
{
    protected readonly B _b;

    public A()
    {
        _b = new B(this);
    }
}

class B
{
    protected readonly A _a;

    public B(A a)
    {
        _a = a;
    }

    public A GetCreator()
    {
        return _a;
    }
}

In this code, GetCreator() returns the instance of A that created the instance of B.

Upvotes: 3

Related Questions