Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# get parent from chlid instance

I try to get the parent Type of a instance. How can I do ?

Example :

public class a
{
     public b { get; set; }
}

public class b
{

}


var a = new a();
a.b = new b();

var parentType = a.b.??GetParentInstanceType()??
like image 475
user1619732 Avatar asked Jul 24 '26 23:07

user1619732


1 Answers

You can't.

You'd need to add a property to the child manually to keep track of the parent:

Here is one way:

public class A
{
    public B<A> Child { get; set; }
}

public class B<T>
{
    public T Parent { get; set; }
}

A a = new A();
a.Child = new B<A>();
a.Child.Parent = a;

Type parentType = a.Child.Parent.GetType();

Of course the problem here is that nothing stops you from forgetting to set Parent or setting the wrong Parent.

like image 181
Servy Avatar answered Jul 27 '26 12:07

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!