Why manipulating 1 object affects the other?

  • Thread starter Thread starter Ryu
  • Start date Start date
R

Ryu

I created 2 objects from a custom collection class.

IntCollection a = new IntCollection();
IntCollection b = new IntCollection();
a.FromInt32Array(someIntArray);
b = a;

However when ever I attempt to remove items from the object a, somehow b
will be affected. Is there a reason why this is happening?
 
Reassigning a variable will cause the loss of whatever data the variable was
originally assigned unless there is another reference to that data.

// Assignment
IntCollection b = new IntCollection();
// Reassignment causes loss of original intCollection that was assigned to b
b = a;
// Now both b and a are variables that reference the intCollection first
assigned to a
 
Reference types don't copy by default. You will have to add copy functionality to your IntCollection and call it. There is an interface called ICloneable which has a single method Clone on it - its defined like this

public interface ICloneable
{
object Clone();
}

You implement this interface to give your type copy semantics and would change your code to this

IntCollection a = new IntCollection();
IntCollection b = (IntCollection)a.Clone();

In your Clone method you would have something like this (I'm making some assumptions of how your IntCollection works from its name)

public object Clone()
{
IntCollection ret = new IntCollection();
foreach( int i in this.myIntStore)
{
ret.Add(i);
}
return ret;
}

One last thing is I remember reading some time ago that there were plans to obsolete IColneable in the next version but I haven't downloaded the latest build so I don't know if that still is the case. If it is you might simply want to add a public method, something like

public IntCollection Copy()
{
// details similar to above
}

and have your calling code as

IntCollection a = new IntCollection();
IntCollection b = a.Copy();

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Yes it is a custom type that I have defined. And Yes I am trying to get a
copy of a into b.
 
Back
Top