Overriding Clone()

  • Thread starter Thread starter Jeff Stewart
  • Start date Start date
J

Jeff Stewart

I have a Stats class derived from HashTable that I want to be cloneable.
But I can't figure out how to override the Clone() method. How do I return
a new Stats object with the same internal hash table as the source object?
All I want is a shallow copy. The best I can come up with is this, but it
seems like a lot of trouble:

public overrides function Clone() as Object
dim returnObj as new Stats = new Stats()

' Insert code to copy each element (shallow only!) of this object's
hashtable to returnObj hashtable
' ...

return returnObj
end function
 
Jeff,
I normally define a constructor that defines a dictionary as a parameter,
then call HashTable's constructor that accepts a dictionary.

Something like:

Public Class MyDictionary

Private Readonly m_hash As Hashtable

Public Sub New(ByVal d As IDictionary)
m_hash = New Hashtable(d)
End Sub

Public Function Clone() As Object
Return New MyDictionary(m_hash)
End Function

End Class

You can make the above constructor Private or Friend if you don't want other
classes to be able to call it.

Hope this helps
Jay
 

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

Back
Top