CloneObject – cloning an object by serializing it to a memory stream

' A reusable function that does object cloning' by serializing it to a memory streamFunction CloneObject(ByVal obj As Object) As Object    ' Create a memory stream and a formatter.    Dim ms As New System.IO.MemoryStream(1000)    Dim bf As New BinaryFormatter(Nothing, _        New StreamingContext(StreamingContextStates.Clone))    ' Serialize the object into the stream.    bf.Serialize(ms, obj)    ' Position streem pointer back to first byte.    ms.Seek(0, SeekOrigin.Begin)    ' Deserialize into another object.    CloneObject = bf.Deserialize(ms)    ' release memory.    ms.Close()End Function' this procedure tests object cloningSub TestCloneObject()    ' create an object graph    Dim p1 As New Person("Joe", "Doe", #1/2/1960#)    Dim p2 As New Person("Ann", "Smith", #3/4/1965#)    p1.Spouse = p2    p2.Spouse = p1    ' Clone it    Dim q1 As Person = DirectCast(CloneObject(p1), Person)    Dim q2 As Person = q1.Spouse    ' Prove that properties were copied correctly.    Console.WriteLine(q1.FirstName & " " & q1.LastName)    Console.WriteLine(q2.FirstName & " " & q2.LastName)    Console.WriteLine("P1 is Q1 = {0}", p1 Is q1)    Console.WriteLine("P2 is Q2 = {0}", p2 Is q2)End Sub' Note: This code is taken from Francesco Balena's' "Programming Microsoft Visual Basic .NET" - MS Press 2002, ISBN 0735613753' You can read a free chapter of the book at ' http://www.vb2themax.com/HtmlDoc.asp?Table=Books&ID=101000

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS