Serialize C# objects of unknown type to bytes using generics Usage example

var qm = new QueueMessage("foo", 99);
var ba = ByteArraySerializer&lt;QueueMessage&gt;.Serialize(qm));


Class that performs the serialization / deserialization

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

namespace Codingoutloud
{
   public static class ByteArraySerializer&lt;T&gt;
   {
      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; }
   }
}
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&lt;T&gt;(this T m)
      {
         using (var ms = new MemoryStream())
         {
            new BinaryFormatter().Serialize(ms, m);
            return ms.ToArray();
         }
      }

      public static T Deserialize&lt;T&gt;(this byte[] byteArray)
      {
         using (var ms = new MemoryStream(byteArray))
         {
            return (T)new BinaryFormatter().Deserialize(ms);
         }
      }
   }
}