Passing a class by value, but reversed?
-
I have a collection class that I've derived from List<MyClass>. I've added no extra functionality to this class except a constructor that clears the list. My problem is this: I'm using the collection in MyClass (the same class that the list is typed for) and I'm doing this
// fill MyClass with some values
col.Add (this);
// where 'col' is my generic List<> dervied classNo problem there it adds the class just fine. The problem arises when I run the code again (it's in a loop), what's happening is that the previous values in the list are changed to the new values that the class has taken on. In effect, if I run the loop, let's say, 5 times the List<> has 5 items in it, but they all have the exact same values. Does anyone have any ideas as to how I can defeat this? I'm thinking there's something better I could be passing into the
Add
function, but I'm not sure what it would be. I was also thinking I could override theAdd
function in my derived collection class and create a deep copy of thethis
parmeter that I passed in, but I'm not sure if that's the right idea. Any ideas and/or help is very appreciated. Thanks. - Aaron -
I have a collection class that I've derived from List<MyClass>. I've added no extra functionality to this class except a constructor that clears the list. My problem is this: I'm using the collection in MyClass (the same class that the list is typed for) and I'm doing this
// fill MyClass with some values
col.Add (this);
// where 'col' is my generic List<> dervied classNo problem there it adds the class just fine. The problem arises when I run the code again (it's in a loop), what's happening is that the previous values in the list are changed to the new values that the class has taken on. In effect, if I run the loop, let's say, 5 times the List<> has 5 items in it, but they all have the exact same values. Does anyone have any ideas as to how I can defeat this? I'm thinking there's something better I could be passing into the
Add
function, but I'm not sure what it would be. I was also thinking I could override theAdd
function in my derived collection class and create a deep copy of thethis
parmeter that I passed in, but I'm not sure if that's the right idea. Any ideas and/or help is very appreciated. Thanks. - AaronCan you make MyClass a struct? That way, it'll behave exactly as you want it to. The only other way is to clone the object, using MemberwiseClone or your custom deep cloning code. Regards Senthil _____________________________ My Blog | My Articles | WinMacro