Monday, April 28, 2014

a C# extension method for serializing a reference type and then deserializing it anew to make a new pointer to a new spot on the heap

This will only work for classes that are decorated with the Serializable() attribute as described here.

public static T MakeNewPointerAndPlaceOnHeap<T>(this T specificObject)
{
   using (var memoryStream = new MemoryStream())
   {
      BinaryFormatter binaryFormatter = new BinaryFormatter();
      binaryFormatter.Serialize(memoryStream, specificObject);
      memoryStream.Position = 0;
      return (T)binaryFormatter.Deserialize(memoryStream);
   }
}

No comments:

Post a Comment