title: Async method returning Task<T> with generic constraint in C#
body: <p>I've implemented a command pattern in <a href="https://github.com/rikkit/lastfm-wp" rel="nofollow noreferrer">a project I'm working on</a>. This is pretty much the current structure:</p>
  
  <pre><code>public class Response
  {
      public bool Success { get; private set; }
  
      public static Response CreateErrorResponse()
      {
          return new Response { Success = false };
      }
  }
  
  public interface ICommand&lt;T&gt; where T : Response
  {
      Task&lt;T&gt; ExecuteAsync();
  }
  
  public abstract CommandBase : ICommand&lt;T&gt; where T: Response
  {
      protected abstract Uri BuildUrl();
      protected abstract Task&lt;T&gt; HandleResponseAsync();
  
      public async override Task&lt;T&gt; ExecuteAsync()
      {
          var url = BuildUrl();
          var httpClient = new HttpClient();
  
          var response = await httpClient.GetAsync(url);
          return await HandleResponseAsync(response);
      }
  }
  </code></pre>
  
  <p>I want to handle any exceptions that could be thrown by the HttpClient, so I want to change CommandBase.ExecuteAsync to something like this...</p>
  
  <pre><code>public async override Task&lt;T&gt; ExecuteAsync()
  {
      var url = BuildUrl();
      var httpClient = new HttpClient();
  
      try
      {
          var response = await httpClient.GetAsync(url);
          return await HandleResponseAsync(response);
      }
      catch (HttpRequestException hex)
      {
          return Response.CreateErrorResponse(); // doesn't compile
      }
  }
  </code></pre>
  
  <p>The compile error I get is "Cannot convert type Response to async return type T". I can't use <code>T.CreateErrorResponse()</code>, as outlined <a href="https://stackoverflow.com/questions/196661/calling-a-static-method-on-a-generic-type-parameter">in this question</a>. </p>
  
  <p>How can I work around this?</p>
  
  <p>Edit to downvoters: whether or not you agree with catching exceptions in a library like this, the question still stands!</p>