C#C
C#4y ago
Hugh

✅ Creating a generic type based on a Type variable rather than a specific type

I've got the following code:

public class QueryResponse<T>
{
  T? Data { get; set; }
  bool Success { get; set; } = false;
  string? ErrorMessage { get; set; }
}


I then want to take this class, and create a Type object that is a QueryResponse<> with the generic type parameter being based on another Type. So something like this. This doesn't work, though as dtoType is a variable, and not a type.

public QueryResponse<T>? GetSomething<T>()
{
  Type dtoType = new T().GetDTOType(); // This will be a different type, but one that a T can be created from
  Type receiveType = typeof(QueryResponse<dtoType>);
  QueryResponse<dtoType>? result = (QueryResponse<dtoType>)JsonSerializer.Deserialize(content, receiveType);
  if(result is null)
  {
    return null;
  }
  return new QueryResponse<T>()
    {
      Data = new T(result.Data),
      Success = true
    };
}


Is this possible?

My overall goal here is to have DTO types and Internal types, and be able to pass the internal types to a function which will automatically convert them to their DTO types (this bit works fine), and then when the function receives the DTO result, have that result converted back to the expected return type and returned. I think that this would be fine, in general, but my problem is that I'm wrapping the return result in the QueryResponse
Was this page helpful?