title: Convert value from string to generic type that is either Guid or int
body: <p>I've got a generic method which converts an id from a string (eg, retrieved from the Value of a HiddenField on an ASP.NET Form) to a target type and does something with it.</p>
  
  <pre><code>private void MyMethod&lt;T&gt;(string rawId, Action&lt;T&gt; doSomethingWithId)
  {
      T id = (T)Convert.ChangeType(rawId, typeof(T));
      doSomethingWithId(id);
  }
  </code></pre>
  
  <p>T will be either Guid or Int32 and the above code falls over (at runtime) when it is Guid, saying that the cast from String to Guid is invalid. </p>
  
  <p>Then I thought I might try to check the type and if Guid, instantiate a new Guid:</p>
  
  <pre><code>var id = default(T);
  if (id is Guid)
      id = new Guid(rawId);
  else
      id = (T)Convert.ChangeType(rawId, typeof(T));
  </code></pre>
  
  <p>now this gives an error (at compile time) that Guid cannot be converted to type T</p>
  
  <p>Not too sure how to work around this. Any suggestions?</p>