3

I'm writing a RESTFUL client library, and part of the return object type depends on the parameters of the request.

For instance, the client has a method called ExecuteCommand, that returns a response object which looks like this:

public class MyResponse
{
   public MyResult Result{ get; set; }
   public MyResponseHeader ResponseHeader { get; set; }
}

Here is the MyResult class:

public class MyResult
{
   public object[] DocumentList{ get; set; }
   public int NumRecords{ get; set; }
   public int Start{ get; set; }
}

What I'd like to do is pass a "Document Type" to the ExecuteCommand method, and have it return the MyResponse object with the MyResult object having the IDocument be the type passed in.

Something to this effect:
MyResponse response = MyClient.ExecuteCommand<MyDocument>(request);

In this instance, what I'd like to have returned is the MyResult with a DocumentList of type MyDocument.

Thanks in advance.

1 Answer 1

5

You could use generics on your classes:

public class MyResponse<T>
{
   public MyResult<T> Result{ get; set; }
   public MyResponseHeader ResponseHeader { get; set; }
}

public class MyResult<T>
{
   public T[] DocumentList{ get; set; }
   public int NumRecords{ get; set; }
   public int Start{ get; set; }
}

Then you can have your ExecuteCommand create your MyResponse using its own T (in this case MyDocument), and using var will make it even easier and more readable:

var response = MyClient.ExecuteCommand<MyDocument>(request);
1
  • This is actually how I coded it, I just wasn't sure about passing the type down the line. Thanks, Drew
    – dhysong
    May 3, 2012 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.