I'm still trying to learn c#, and while doing so I am trying to
convert some C++ code to C#. Doing so has kind of challenged my
understanding of the way values and references work in C# when i'm
tyring to duplicate C++ items that use pointers, such as a linked
list.
In the c++ code that i'm trying to convert, I have a linked list of
objects that keeps track of parent, child and sibling objects. My C#
version of it seems to be going ok until I get to a function where I
remove all of the child objects. In the C++ version the list is
traversed and the child objects get deleted, but i'm not sure how to
do it properly in C#.
Here is a bit of sample code of what I have done is C#, followed by
the C++ version of the function that is getting me confused:
Class MyObject
{
MyObject m_ChildObject;
MyObject m_NextSiblingObject;
MyObject m_PreviousSiblingObject;
MyObject m_ParentObject;
//I then have a series of Get and Set methods for
setting the above objects
Public void AddChildObject( MyObject childObjectToAdd)
{
childObjectToAdd.SetParentObject(this);
//I check to see if this is the first child for this object
If (m_ChildObject == null)
{
M_ChildObject = childObjectToAdd;
}
else //this isn’t the first child for this object
{
MyObject tempObject = this.GetChildObject();
While (tempObject.GetNextSiblingObject() != null)
{
tempObject = tempObject.GetNextSiblingObject();
}
tempObject.SetNextSiblingObject(childObjectToAdd);
childObjectToAdd.SetPreviousSiblingObject(tempObje ct);
}
}
Public void RemoveAllChildObjects()
{
MyObject tempObject = this.GetChildObject();
While(tempObject != null)
{
MyObject nextObject = tempObject.GetNextSiblingObject();
//*now I want to delete or set to null each object in the linked
list
tempObject = nextObject;
}
}
}
I don’t know if it is helpful to look at, but here is the c++ version
of the RemoveAllChildObjects that I am trying to duplicate in C#
Public boid RemoveAllChildObjects()
{
MyObject* tempObject = this->GetChildObject();
While(tempObject)
{
MyObject* nextObject = tempObject->GetNextSiblingObject();
SAFE_DELETE(tempObject);
tempObject = nextObject;
}
}