title: C# Google.ProtocolBuffers -> Generic parse
body: <p>I receive a byte[]  which represents a message serialized using protocol buffer.  </p>
  
  <p>I know the type of the message, it is sent along side the byte[], and i can easily parse it.</p>
  
  <pre><code> MyMessage.ParseFrom(byte[]) . 
  </code></pre>
  
  <p>The thing is i do not like repetitive code. Especially when all i wan't this piece of code to transform the byte[] into some derivation of the same type. </p>
  
  <p>So i made a generic parse method :</p>
  
  <pre><code>    public static T As&lt;T&gt;(byte[] body)
      {
          var parser = GetParseMethod&lt;T&gt;();
          return (T)parser.Invoke(null, new object[] { body });
      }
  
       private static MethodInfo GetParseMethod&lt;T&gt;()
      {
          var type = GetType(typeof(T).Name);
          var methods = type.GetMethods(); // 
          var parseFromMethod = methods.Where(m =&gt; m.Name == "ParseFrom");
          var parseFromByteArrMethod = parseFromMethod.Single(m =&gt; m.GetParameters().Length == 1 &amp;&amp; m.GetParameters().First().ParameterType == typeof(byte[]));
          return parseFromByteArrMethod;
      }
  
       private static Type GetType(string typeName)
      {
          var type = Type.GetType("ReportingApi.Proto." + typeName + ", ReportingApi.Proto", true, true);
          return type;
      }  
  </code></pre>
  
  <p>I am unable to find a built in way to parse messages in a generic manner as iv'e implemented above. </p>
  
  <p><strong>Some additional info for this question .</strong></p>
  
  <p>1) I generated my code from a "proto2" file to C# 
     using proto-compiler-3.0.0-alpha3   </p>
  
  <p>protoc --csharp_out=../ ReportingMessages.proto  </p>
  
  <p>2) I am using Google.ProtocolBuffers  2.4.1.555</p>
  
  <p>thanks in advance.  </p>