title: Get generic type in Async callback
body: <p>I'm writing a library that communicates with a JsonRpc service via HTTP. All HTTP operations are done async by design.</p>
  
  <p>Each command sent to the JsonRpc service will result in the server responding with a list of items. </p>
  
  <p>The process is user calls GetXXXX method and provides a callback (Very cut down version):</p>
  
  <pre><code>GetArtists(userCallback)
  {
     var state = new AsyncState&lt;Artist&gt;(userCallback);
  
     jsonRpcClient.post(uri, internalCallback, AsyncState);
  }
  
  
  GetArtistsInternalCallback(httpStatusCode, responseBody, asyncState)
  {
      var realState = asyncState as AsyncState&lt;Artist&gt;.
  
  
     // parse response body in to list of Artists
  
  
     realState.UserCallback(List&lt;Artist&gt;);
  }
  
  
  UserCallback(List&lt;Artist&gt; artists)
  {
     User can do something with result
  }
  </code></pre>
  
  <p>Now the Async state is generic, so if I had a method called GetAlbums for example the user would supply a callback with a signature of UserCallback(List albums) etc.</p>
  
  <p>This is working fine but now what I want to do is make the InternalCallback generic. I have a lot of GetXXXX methods to implement and they all follow the exact same pattern.</p>
  
  <p>I want my AsyncState to have a delegate on it that processes the server response so the InternalCallback would look something like:</p>
  
  <pre><code>InternalCallback(httpStatusCode, responseBody, asyncState)
  {
      var realState = asyncState as AsyncState&lt;MAGICALLY-FIGURE-OUT-TYPE&gt;.
  
      *Do generic work here*
  
       var listOfItems = asyncState.ProcessServerResponse(responseBody)
  
       realState.UserCallback(List&lt;MAGIC-TYPE&gt; listOfItems);
  }
  </code></pre>
  
  <p>So this would allow me to stop repeating the InternalCallback for every GetXXX method (Only thing that changes is the type).</p>
  
  <p>But I now have the problem of how do I figure out the type of the state object in the callback? Up until now it's explicitly declared i.e. GetArtistsInternalCallback knows it's working with Artists but if I had a generic callback how would it figure out the type?</p>
  
  <p>EDIT: Also if it makes any difference the Artist and Album types are derived from a common base class called MediaItem.</p>
  
  <p>Cheers,</p>
  
  <p>Tyler</p>