patterncsharpModerate
Serialize C# objects of unknown type to bytes using generics
Viewed 0 times
objectsserializeunknowntypebytesusinggenerics
Problem
Usage example
Class that performs the serialization / deserialization
Example of an object we would serialize
var qm = new QueueMessage("foo", 99);
var ba = ByteArraySerializer.Serialize(qm));Class that performs the serialization / deserialization
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Codingoutloud
{
public static class ByteArraySerializer
{
public static byte[] Serialize(T m)
{
var ms = new MemoryStream();
try
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, m);
return ms.ToArray();
}
finally
{
ms.Close();
}
}
public static T Deserialize(byte[] byteArray)
{
var ms = new MemoryStream(byteArray);
try
{
var formatter = new BinaryFormatter();
return (T)formatter.Deserialize(ms);
}
finally
{
ms.Close();
}
}
}
}Example of an object we would serialize
using System;
namespace Codingoutloud
{
[Serializable]
public class QueueMessage
{
public QueueMessage() {}
public QueueMessage(string name, int id)
{
Name = name;
Id = id;
}
public string Name { get; set; }
public int Id { get; set; }
}
}Solution
Your methodology is solid on the generics front. Highly recommend using
using statements rather than try..finallys. I also converted the methods to extension methods.namespace Codingoutloud
{
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class ByteArraySerializer
{
public static byte[] Serialize(this T m)
{
using (var ms = new MemoryStream())
{
new BinaryFormatter().Serialize(ms, m);
return ms.ToArray();
}
}
public static T Deserialize(this byte[] byteArray)
{
using (var ms = new MemoryStream(byteArray))
{
return (T)new BinaryFormatter().Deserialize(ms);
}
}
}
}Code Snippets
namespace Codingoutloud
{
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class ByteArraySerializer
{
public static byte[] Serialize<T>(this T m)
{
using (var ms = new MemoryStream())
{
new BinaryFormatter().Serialize(ms, m);
return ms.ToArray();
}
}
public static T Deserialize<T>(this byte[] byteArray)
{
using (var ms = new MemoryStream(byteArray))
{
return (T)new BinaryFormatter().Deserialize(ms);
}
}
}
}Context
StackExchange Code Review Q#7673, answer score: 12
Revisions (0)
No revisions yet.