title: Generic Parse Method without Boxing
body: <p>I am trying to write a generic Parse method that converts and returns a strongly typed value from a NamedValueCollection.  I tried two methods but both of these methods are going through boxing and unboxing to get the value.  Does anyone know a way to avoid the boxing?  If you saw this in production would you not like it, how bad is it for performance?</p>
  
  <p>Usuage:</p>
  
  <pre><code>var id = Request.QueryString.Parse&lt;int&gt;("id");
  </code></pre>
  
  <p>Attempt #1:</p>
  
  <pre><code>public static T Parse&lt;T&gt;(this NameValueCollection col, string key)
  {
      string value = col[key];
  
      if (string.IsNullOrEmpty(value))
          return default(T);
  
      if (typeof(T) == typeof(int))
      {
          //return int.Parse(value); // cannot convert int to T
          //return (T)int.Parse(value); // cannot convert int to T
          return (T)(object)int.Parse(value); // works but boxes
      }
      if (typeof(T) == typeof(long))
      {
          return (T)(object)long.Parse(value); // works but boxes
      }
      ...
  
      return default(T);
  }
  </code></pre>
  
  <p>Attempt #2 (using reflection):</p>
  
  <pre><code>public static T Parse&lt;T&gt;(this NameValueCollection col, string key)
  {
      string value = col[key];
  
      if (string.IsNullOrEmpty(value))
          return default(T);
  
      try
      {
          var parseMethod = typeof(T).GetMethod("Parse", new Type[] { typeof(string) });
  
          if (parseMethod == null)
              return default(T);
  
          // still boxing because invoke returns an object
          var parsedVal = parseMethod.Invoke(null, new object[] { value });
          return (T)parsedVal;
      }
      // No Proper Parse Method found
      catch(AmbiguousMatchException) 
      {
      }
  
      return default(T);
  }
  </code></pre>