I have a program where I have three classes A, B and C.
A contains a member that is a list of B, and B consists of a member that is a list of C.
A contains a method that is called RemoveB(), and similarly B contains a method that is called RemoveC(). RemoveB() and RemoveC() remove the first element of the BList and the CList respectively.
The following is what it all looks like:
class A
{
...
List<B> BList;
...
public void RemoveB()
{
this.BList.Removeat(0)
}
}
class B
{
...
List<C> CList;
...
public void RemoveC()
{
this.CList.Removeat(0)
}
}
class Trial
{
...
}
In my main function I first populate BList and the CList in each of these BList elements. There are N elements in BList and each of the BList elements contains M elements in CList. Then I do the following.
A aObject = new A(); // Populates BList and CList.
for(int i = 0; i < N; i++)
{
Console.WriteLine("BList: {0} ({1})", i, aObject.BList[0].Count);
for (int j = 0; j < M; j++)
{
Console.WriteLine("CList: {0}", j);
aObject.BList[0].RemoveC();
}
aObject.RemoveB();
}
When I do this, I get the following problem. When I try to remove elements in CList belonging to element BList[0], the corresponding elements in CList in BList[1], BList[2]… BList[N-1] are also removed.
The following is the output I see from the running the program.
BList 0 (M)
CList 0
CList 1
CList 2
.
.
.
CList M-1
BList 1 (0)
BList 2 (0)
BList 3 (0)
.
.
.
BList N-1 (0)
Could someone tell me why this could be happening? Am I doing some fundamental mistake somewhere.
Looks like a problem with how you’re creating the B and C elements in the A constructor. Are you using the new keyword to create each individual B element and C element and list of C elements? If you’re just copying them at some point, then they may still be the same actual object in memory, and changing or deleting one of them could do the same thing to the others as well.