ICloneable

M

Michael D. Ober

In VB 2005, the ICloneable interface requires the following:

Class foo
Implements ICloneable

Public Function Clone() as Object Implements System.ICloneable.Clone
' return new_object of type foo
End Function

End Class

However, with Option Strict On, to use this requires

newfoo as foo = CType(oldFoo.Clone(), foo)

This takes additional CPU cycles at runtime - first to coerce foo's clone to
object and then to coerce the clone back to foo.

In the case of a non-inheritable object with a Clone function, is there any
reason to use:

Class foo

Public Function Clone() as foo
' return new_object of type foo
End Function

End Class

Now you can say

option strict on

newfoo = oldFoo.Clone()

Thanks,
Mike Ober.
 
J

Joshua Flanagan

It seems like you just explained the reason to use a strongly typed
version (to avoid the casting to/from object). Did you mean "is there
any reason NOT to use:" ?

The only reason I would say not to use the strongly typed version (as
foo) is if other objects expect your class to implement ICloneable. If
you need to implement ICloneable, you will need to create a Clone() that
returns object. In C# you could have both by explicitly implementing
ICloneable.Clone() - I'm not positive how you would do it in VB.NET. I
think you would have to rename your strongly typed Clone() to something
else, like FooClone().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top