2

I'm implementing a customized Graph algorithm in vb.net, and I'm having the following problem:

Supose the code:

dim col as new collection
dim myC as new system.collections.genericList(of myClass)

dim obj1 as new myClass
dim obj2 as new myClass

myC.add(obj1)
myC.add(obj2)

dim myC2 as new system.collections.generic.list(of myClass)

myC2 = myC

col.add(myc2)

'In the next statement, the myC2 inside col collection will be decreased to contain
'only obj1, like myC. I supose this is for myC and myC2 contains only a pointer to
'objects obj1 and obj2 as well col contains pointers to myC and myC2
myC.remove(obj2)

'The problem is that I have to only copy myC to myC2, like a ByVal argument in a function,
'instead a ByRef argument, in order to mantain a copy of objects in myC2 while these
'objects should be removed from myC. How should I do it?

Thanks for helping...

Alex
  • 3,325
  • 11
  • 52
  • 80

2 Answers2

8

You can pass myC as an argument to myC2's constructor:

Dim myC2 As New System.Collections.Generic.List(Of [MyClass])(myC)

This will initialize a new list with the same elements as myC.

tore
  • 300
  • 2
  • 5
1

I agree that ICloneable provides the best interface to expose cloning behavior but recommend looking into AutoMapper to perform the actual work. AutoMapper will allow you to dynamically map types without all of the A.Z = B.Z code.

And, when mapping one collection to another, AutoMapper will automatically create copies of the source items. In fact, you can use a statement similar to the following to create the second collection on-the-fly:

var secondCollection = Mapper.DynamicMap<Collection<Items>>(firstCollection);

You can easily put this inside the ICloneable.Clone method like:

object ICloneable.Clone()
{
    return Mapper.DynamicMap<ThisType>(this);
}

(DynamicMap is a convenient method that allows you to map objects without previously defining the mapping. This is valuable if you don't have to define any deltas when mapping as would be the case when simply cloning an object.)

This is also a good way of implementing Clone when you are working on platforms that don't support the BinaryFormatter that is typically used.

Hope that helps.

SonOfPirate
  • 5,642
  • 3
  • 41
  • 97
  • 1
    Microsoft recommends that ICloneable not be implemented (in Framework Design Guidelines). The reason is that it does not specify if it's a deep-copy or shallow-copy. – TrueWill Nov 26 '11 at 01:22
  • True, this is a standard that you have to determine (guidelines are guidelines). Most consider it to be a deep copy. I've implemented a similar ICopyable interface that I use with entities (that have identity) which will create a copy of the entity with a new identity. – SonOfPirate Nov 28 '11 at 18:10