How to clone an object?

R

Rob R. Ainscough

Is there an easy way to clone an object? What I've done in the past is
write my own Clone method for each class i create and then just assign
property values across objects.

I was hoping VS 2005 would provide a object clone feature.
 
H

Herfried K. Wagner [MVP]

Rob R. Ainscough said:
Is there an easy way to clone an object? What I've done in the past is
write my own Clone method for each class i create and then just assign
property values across objects.

I was hoping VS 2005 would provide a object clone feature.

You could utilize serialization for this purpose:

\\\
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
..
..
..
Public Sub Test()
Dim x As New Foo("Bill", #12/12/2002#)
Dim y As Foo = DirectCast(x.Clone(), Foo)
MsgBox(y.Name & ", " & y.Value.ToString())
End Sub
..
..
..
<Serializable()> _
Public Class Foo
Implements ICloneable

Private m_Name As String
Private m_Value As Object

Public Sub New(ByVal Name As String, ByVal Value As Object)
Me.Name = Name
Me.Value = Value
End Sub

Public Function Clone() As Object Implements System.ICloneable.Clone
Dim m As New MemoryStream()
Dim f As New BinaryFormatter()
f.Serialize(m, Me)
m.Seek(0, SeekOrigin.Begin)
Return f.Deserialize(m)
End Function

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

Public Property Value() As Object
Get
Return m_Value
End Get
Set(ByVal Value As Object)
m_Value = Value
End Set
End Property
End Class
///
 

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