C # Passing a Type to a Child Class

I am writing a RESTFUL client library, and part of the type of the returned object depends on the request parameters.

For example, the client has an ExecuteCommand method that returns a response object that 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 would like to do is pass the “Document Type” to the ExecuteCommand method and return it a MyResponse object with a MyResult object of type IDocument.

Something like that:
  MyResponse response = MyClient.ExecuteCommand<MyDocument>(request);

In this case, what I would like to return is MyResult with a DocumentList of type MyDocument.

Thanks in advance.

+3
source share
1 answer

You can use generics in 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 create ExecuteCommand ExecuteCommandusing your own T(in this case MyDocument), and using var will make it even easier and more intuitive:

var response = MyClient.ExecuteCommand<MyDocument>(request);
+5
source

All Articles