Your methodology is solid on the generics front. Highly recommend using using statements rather than try..finallys and I also hoisted the BinaryFormatter creation out to relieve any GC pressure. Finally, I also converted themthe methods to extension methods. Your methodology is solid on the generics front.
namespace Codingoutloud
{
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class ByteArraySerializer
{
private static readonly BinaryFormatter formatter = new BinaryFormatter();
public static byte[] Serialize<T>(this T m)
{
using (var ms = new MemoryStream())
{
formatternew BinaryFormatter().Serialize(ms, m);
return ms.ToArray();
}
}
public static T Deserialize<T>(this byte[] byteArray)
{
using (var ms = new MemoryStream(byteArray))
{
return (T)formatternew BinaryFormatter().Deserialize(ms);
}
}
}
}