title: Protobuf-net serialization/deserialization
body: <p>I checked but seem to be unable to see how to directly serialize a class to a byte array and subsequently deserialize from a byte array using Marc Gravell's protobuf-net implementation. </p>
  
  <p>Edit: I changed the question and provided code because the original question of how to serialize into byte[] without having to go through stream was admittedly trivial. My apologies.</p>
  
  <p>Updated Question: Is there any way to not have to deal with generics and instead infer the type of the property "MessageBody" through reflection when it is passed through the constructor? I assume I cannot serialize object type, correct? The current solution looks very cumbersome in that I need to pass in the type of the MessageBody each time I instantiate a new Message. Is there a sleeker solution to this? </p>
  
  <p>I came up with the following:</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          Message&lt;string&gt; msg = new Message&lt;string&gt;("Producer", "Consumer", "Test Message");
  
          byte[] byteArray = msg.Serialize();
          Message&lt;string&gt; message = Message&lt;string&gt;.Deserialize(byteArray);
  
          Console.WriteLine("Output");
          Console.WriteLine(message.From);
          Console.WriteLine(message.To);
          Console.WriteLine(message.MessageBody);
  
          Console.ReadLine();
  
      }
  }
  
  [ProtoContract]
  public class Message&lt;T&gt;
  {
      [ProtoMember(1)]
      public string From { get; private set; }
      [ProtoMember(2)]
      public string To { get; private set; }
      [ProtoMember(3)]
      public T MessageBody { get; private set; }
  
      public Message()
      {
  
      }
  
      public Message(string from, string to, T messageBody)
      {
          this.From = from;
          this.To = to;
          this.MessageBody = messageBody;
      }
  
      public byte[] Serialize()
      {
          byte[] msgOut;
  
          using (var stream = new MemoryStream())
          {
              Serializer.Serialize(stream, this);
              msgOut = stream.GetBuffer();
          }
  
          return msgOut;
      }
  
      public static Message&lt;T&gt; Deserialize(byte[] message)
      {
          Message&lt;T&gt; msgOut;
  
          using (var stream = new MemoryStream(message))
          {
              msgOut = Serializer.Deserialize&lt;Message&lt;T&gt;&gt;(stream);
          }
  
          return msgOut;
      }   
  }
  </code></pre>
  
  <p>What I like to get to is something such as: </p>
  
  <p>Message newMsg = new Message("Producer", "Consumer", Foo);
  byte[] byteArray = newMsg.Serialize();</p>
  
  <p>and
  Message msg  = Message.Deserialize(byteArray);</p>
  
  <p>(where Deserialize is a static method and it always deserializes into an object of type Message and only needs to know what type to deserialize the message body into).</p>