title: Serialize object[] with Protobuf-net
body: <p>I would like to serialize and deserialize some values stored in an object array. </p>
  
  <pre><code>public class Sample
  {
      public object[] Data;
  }
  </code></pre>
  
  <p>I know at run-time what types to expect in the array. In effect I want to treat Data inside of Sample as a message stream. </p>
  
  <p>Individually, I know I can use <code>Serializer.NonGeneric.SerializeWithLengthPrefix</code> to write each object out using a <code>PrefixStyle.Base128</code> and make a Prefix->Type map for the Deserialise Type-Resolver. See <a href="https://stackoverflow.com/questions/8601647/what-is-protobuf-net-serializewithlengthprefix-tag-argument-for">What is protobuf-net SerializeWithLengthPrefix tag argument for?</a></p>
  
  <p>What I'm struggling with is actually getting protobuf-net to do that automatically for me and then nesting that behavior within a an encompassing message. As far as I can tell the resulting messages in the stream would be perfectly valid.   </p>
  
  <p>For example; lets say I have this array of objects: </p>
  
  <pre><code>new object[]
  {
      "Hello",
      42,
      0.3529321,
      true
  }
  </code></pre>
  
  <p>and the tag-map </p>
  
  <pre><code>var typeToTag = new Dictionary&lt;Type, int&gt;()
  {
      {typeof (string), 1},
      {typeof (int), 2},
      {typeof (double), 3},
      {typeof (bool), 4},
  };
  </code></pre>
  
  <p>I can write each of them to a stream with the non-generic <code>SerializeWithLengthPrefix</code> </p>
  
  <pre><code>foreach (var value in data)
      Serializer.NonGeneric.SerializeWithLengthPrefix(
          stream,
          value,
          PrefixStyle.Base128,
          typeToTag[value.GetType()]);
  </code></pre>
  
  <p>now, separately (stored independently) I know there are 4 values in that message and I know (at run-time) the map</p>
  
  <pre><code>var tagToType = new Dictionary&lt;int, Type&gt;()
  {
      {1, typeof (string)},
      {2, typeof (int)},
      {3, typeof (double)},
      {4, typeof (bool)},
  };
  </code></pre>
  
  <p>then I can deserialise with </p>
  
  <pre><code>var expectedElements = 4;
  
  var readObjects = new object[expectedElements];
  
  for (int i = 0; i &lt; expectedElements; i++)   
      Serializer.NonGeneric.TryDeserializeWithLengthPrefix(
          stream,
          PrefixStyle.Base128,
          (t) =&gt; tagToType[t], out readObjects[i]);
  
      }
  }
  </code></pre>
  
  <p>That all works perfectly. </p>
  
  <p>My issue is I want to bundle the above behavior so that protobuf-net uses it (serialize/deserialize the object stream with the given tag maps) when I try to serialise and deserialize an instance of <code>Sample</code> - effectively a message with a nested message stream.</p>
  
  <p>Any help in steering me in the right direction is welcome. :)</p>