O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Create a Type-Safe Clone Method

Problem

You want to create a Clone method that returns an object of the correct type. However, the ICloneable.Clone method always returns a generic object.

Solution

Make the method that implements ICloneable.Clone private, and add another, strongly typed Clone method.

Discussion

The ICloneable interface always returns a generic System.Object reference, which means that the client must use casting code to convert the object to the appropriate type. However, you can remove this extra step by adding a strongly typed Clone method, as shown here.

Public Class Person Implements ICloneable Private _FirstName As String Private _LastName As String ' (Property procedure and constructor code omitted.) Private Function CloneMe() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required