Deep clone with MemoryStream : Memory Stream « File Stream « C# / C Sharp






Deep clone with MemoryStream

 

//--------------------------------------------------------------------------
// 
//  Copyright (c) Microsoft Corporation.  All rights reserved. 
// 
//  File: Utilities.cs
//
//--------------------------------------------------------------------------

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ParallelMorph
{
    /// <summary>Helper utilities.</summary>
    public static class Utilities
    {
        /// <summary>Deep clones a serializable object.</summary>
        /// <typeparam name="T">Specifies the type of the object to be cloned.</typeparam>
        /// <param name="source">The source object to be cloned.</param>
        /// <returns>The generated deep clone.</returns>
        public static T DeepClone<T>(T source) where T : class
        {
            using (MemoryStream ms = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(ms, source);
                ms.Position = 0;
                return (T)formatter.Deserialize(ms);
            }
        }

    }
}

   
  








Related examples in the same category

1.Create a MemoryStream
2.MemoryStream.Write
3.Use MemoryStream and BinaryWriter to convert decimal to byte arrayUse MemoryStream and BinaryWriter to convert decimal to byte array
4.Use MemoryStream and BinaryReader to convert Byte array to decimalUse MemoryStream and BinaryReader to convert Byte array to decimal
5.MemoryStream.ToArray, MemoryStream.ReadDecimal
6.Deep Copy with MemoryStream
7.Memory-Mapped Files
8.Using MemoryStream to Serialize and Desirialize
9.Convert a string into an array of bytes