© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
35 replies
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; }
}
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
Type
object that is a
QueryResponse<>
QueryResponse<>
with the generic type parameter being based on another
Type
Type
. So something like this. This doesn't work, though as
dtoType
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
    };
}
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
QueryResponse
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Variable type passed to generic
C#CC# / help
2y ago
Xml generic type deserialisation based on attribute
C#CC# / help
13mo ago
Using pointers as generic a generic type
C#CC# / help
4y ago
✅ Generic function with conditional type based logic inside
C#CC# / help
2y ago