title: Using System.Type to call a generic method
body: <p>I am using C#/.NET 4.0 and a Protocol Buffers library (protobuf-net) which provides the following functionality.</p>
  
  <pre><code>public static class Serializer {
      public static void Serialize&lt;T&gt;(Stream destination, T instance);
      public static void Serialize&lt;T&gt;(SerializationInfo info, T instance);
      public static void Serialize&lt;T&gt;(XmlWriter writer, T instance);
      public static void Serialize&lt;T&gt;(SerializationInfo info, StreamingContext context, T instance);
      public static T Deserialize&lt;T&gt;(Stream source);
  }
  </code></pre>
  
  <p><strong>I need to wrap two of these calls with non-generic equivalents.</strong> Specifically, I want</p>
  
  <pre><code>void SerializeReflection(Stream destination, object instance);
  object DeserializeReflection(Stream source, Type type);
  </code></pre>
  
  <p>that simply call the respective generic members of <code>Serializer</code> at runtime. <strong>I have gotten the <code>DeserializeReflection</code> method to work with the following code:</strong></p>
  
  <pre><code>public static object DeserializeReflection(Stream stream, Type type)
  {
      return typeof(Serializer)
          .GetMethod("Deserialize")
          .MakeGenericMethod(type)
          .Invoke(null, new object[] { stream });
  }
  </code></pre>
  
  <p>The <code>SerializeReflection</code> method is what is causing me trouble. I at first tried the following code:</p>
  
  <pre><code>public static void SerializeReflection(Stream stream, object instance)
  {
      typeof(Serializer)
          .GetMethod("Serialize")
          .MakeGenericMethod(instance.GetType())
          .Invoke(null, new object[] { stream, instance });
  }
  </code></pre>
  
  <p>The problem is that the part between <code>typeof(Serializer)</code> and <code>.Invoke(...)</code> is not working. The call to <code>GetMethod("Serialize")</code> gets me an <code>AmbiguousMatchException</code>, because there are four methods named "<code>Serialize</code>."</p>
  
  <p>I then tried using the overload of <code>GetMethod</code> that takes an array of <code>System.Type</code> to resolve the binding:</p>
  
  <pre><code>GetMethod("Serialize", new[] { typeof(Stream), instance.GetType() })
  </code></pre>
  
  <p>But this just made the result of <code>GetMethod</code> <code>null</code>.</p>
  
  <p><strong>How can I use reflection to get the <code>MethodInfo</code> for <code>void Serializer.Serialize&lt;T&gt;(Stream, T)</code>, where <code>T</code> is <code>instance.GetType()</code>?</strong></p>