Whats the best way for a child class to know about its parent class

M

moondaddy

I'm using WPF and c#. Whats the best way for a child class to know about
it's parent class? For examle

class ParentClass : CollectionBase
{
// code...

class ChildClass
{
// code...

void SomeMethod()
{
if(myParentClass.Count>0)
{
//do something
}
}

}
}

Thanks.
 
W

Walter Wang [MSFT]

Hi moondaddy,

The ChildClass will not have any reference to the ParentClass. Consider
this: an instance of ChildClass could be added to multiple ParentClass.

If you could guarantee an instance of ChildClass could only be added to one
ParentClass. You could create a public property in the ChildClass to hold
the reference to ParentClass and let the ParentClass.Add or Insert to set
this reference.

class ChildClass
{
private ParentClass _parent;

internal ParentClass Parent
{
get { return _parent; }
set { _parent = value; }
}

}

class ParentClass : CollectionBase
{
public int Add(ChildClass item)
{
if (item != null) item.Parent = this;
return List.Add(item);
}

public void Insert(int index, ChildClass item)
{
if (item != null) item.Parent = this;
List.Insert(index, item);
}
}



Regards,
Walter Wang ([email protected], remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top