Home > front end >  C# multiple generic types in method input and output collection
C# multiple generic types in method input and output collection

Time:09-17

I have generic query method which looks like below

List<T> Query<T>(QueryModel query) where T : BaseClass 
{
      // get data and Deserialize by T
}

// where T is Table DTO, to Deserialize response by T

Now I want to implement multiple query execution parallelly

for that I need to have multiple type parameters in response and input and want to achieve something like this:

List<T1, T2, T3> Query<T1, T2, T3>(List<QueryModel> queries) 
     where T1: BaseClass,
     where T2: BaseClass,
     where T3: BaseClass 
{
     // for each query in queries
     // get data for each query and 
     // deserialize each by T1/T2/T3 accordingly
     // return all responses in single generic collection
}

here in above example 3 queries can be there, each can be deserialized by provided typed parameters accordingly.

but I believe we can't have more than one typed parameters with collections like List, Not sure how this can be achieved.

PS : I can go for limited set of Tables for now to query, e.g query with 3-4 typed parameters, so can add overload with fix number of typed parameters, It would be great if there is some solution for n number of typed parameters.

CodePudding user response:

You could perhaps write it like

(T1 r1, T2 r2, T3 r3) Query<T1, T2, T3>(QueryModel q1,QueryModel q2,QueryModel q3 )

This would not allow an arbitrary number of queries, but you cannot have a variable number of generic arguments anyway, so I don't see any way to do that while keeping the generic types.

CodePudding user response:

From C# 7.0 I believe that you can use tuples e.g.

    List<(T1, T2, T3)> Get<T1,T2,T3>(string query) where T1 : BaseClass, new() where T2 : BaseClass, new() where T3 : BaseClass, new()
    {
        var result = new List<(T1, T2, T3)>
        {
            ( new T1(), new T2(), new T3()),
            ( new T1(), new T2(), new T3())

        };

        return result; 
    }
  • Related