one object's private variable affecting another object's, but it shouldn't [modified]
-
Hi. My problem is the following. I have a class that contains a "MakeByteArray" function. I have many objects of that class. Inside that function, I have a private variable, that is NOT static. It seems that when I put all these objects in other objects, and then into a list, and I iterate through every object, the PRIVATE variable that i use in "MakeByteArray" is altered depending on what the value was in the previous object. This makes no sense since the objects don't know about each other, and the variable is not static. In short, the following happnes: Print contents of object 1; object 1 has private variable "priv_var" that is a short and has a value of "X"; correct contents printed Print contents of object 2; object 2 has private variable "priv_var" that is a short and has a value of "Y"; incorrect contents printed; "Y" should have been printed, but, "Y+X" was printed instead (note that "X" is the value of "priv_var" in object 1) OR, if I reset priv_var to 0 at end of MakeByteArray() in object 1, then sometimes the value (0) carries over to object 2's priv_var (when it shouldn't) How do I know that object 2's "priv_var" got the value "Y+X" from object 1, and NOT from somewhere else? I did tests. When object 1's value changed, so did object 2's. I tried many different (short) values, and the results were the same. However, this doesn't happen always. I know *when* it happens, but I don't know *why*. I this summarizes my problem, however, if you want to see more (very long), including code, scroll down. Oh, forgot to mention, I am using Visual Studio 2005, Windows XP, on an intel machine. I'd appreciate any help with this. Thank you. ----------------------------------------------------------------------------------------------- Before you start, I apologize in advance for the formatting (or lack of) of my code. Now, my code. This is the code for the class whose objects are put into another object. namespace ConsoleApplication1 { public class MyPara : MyFormat { public static long totalSum = 0; // public for testing purposes protected short rc; public MyPara() { /* various variables initialized here */ rc = 0; } /* more constructors here; all of them do rc = 0; multiple (irrelevant) functions here as well; */ public bool IncRc() { rc++; } public byte[] MakeByteArray() { shor