How to Get Parent Object in case of compostion

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello

I need to get a parent object of an object. I how to get the instance of an
object in which current object created.

is it possible in c# ?

Thank
 
I need to get a parent object of an object. I how to get the instance of an
object in which current object created.

is it possible in c# ?

The easiest way is to pass it in as an argument to the constructor.
You have to keep in mind that the object may be created from a static
method in which case there is no "parent object".


Mattias
 
is it not posiible by reflection or such other thing ? I don't able to pass
it in cunstruction due to some reason ?

please help

BL
 
BL said:
is it not posiible by reflection or such other thing ? I don't able to
pass
it in cunstruction due to some reason ?

please help

Are you referring to a struct or a class? A class instance is not actually
created "in" another object, it is created independently in the managed
heap. A struct may either be created "in" a class instance on the heap,
"in" a box or array independently on the heap, in global memory, or on the
stack, or "in" another struct which can be again in any of these locations.

In native C++, and it was directly declared exactly once and inside only one
class, then you could use __offsetof to get to the parent pointer.

In the managed world, if you are talking about a struct on the managed heap
(by embedding inside a class, box, or array), then one ought to be able to
get a handle to the enclosing allocation unit tracked by the garbage
collector (the one which pinning the struct would fix in place).

If you are going to get any help, you need to show some code, because your
grammar and spelling are too poor for us to understand exactly what you
mean.
 
Hi

Sorry for mistakes

The following is an example of my requirement. could you please help me what
code/logic I should be write in GetParent() method to get it run ?

public class A()
{
public A{}

B objB = new B();
}

Public Class B()
{
public B()

A objParentofThis = GetParent(this)

private A GetParent(B ObjB)
{
// want to write some code here so this function
// should be return the instance of parent object of this object.
//I am sure the parent object type will be "A"
}

}

BL
 
BL said:
Sorry for mistakes

The following is an example of my requirement. could you please help me what
code/logic I should be write in GetParent() method to get it run ?

You can't, without passing it in as a parameter to the constructor.
Objects don't remember who created them normally.
 
Back
Top