Jaydeep Shil
Jaydeep Shil

Reputation: 1959

Generic Type Return and Argument order in c#

I want to create a generic method like below :

Task<Response> PerformSomeAction<Request, Response>(
                Request request, string token) 
                where Response : ResponseModel
                where Request : RequestModel;

is there any order that we need to maintain while declaring .

can we write like below also?

Task<Response> PerformSomeAction<Response, Request>(
                    Request request, string token) 
                    where Response : ResponseModel
                    where Request : RequestModel;

is both are same?

Upvotes: 0

Views: 675

Answers (1)

TheGeneral
TheGeneral

Reputation: 81573

Update

There is no order needed on declaring generic parameters, however write them the way they seem logical, your first examples (to me seems more logical).

Original

I was heading around the garden path of this one, and totally misread the question

Your calling code cannot switch the generic parameters because you have constraints on the method. in this case the only option you have is to make different overloads of the same method.

That's to say, the first generic parameter, is expecting a type of RequestModel as you have denoted in your constraints, you can't send it a ResponseModel. E.g

PerformSomeAction<SomeResponse,SomeRequest>()  

You can (however) overload signatures and generic parameters though

Exmaple

public class SwitchAroo
{
    Task<Response> PerformSomeAction<Request, Response>(
                    Request request, string token) 
                    where Response : ResponseModel
                    where Request : RequestModel { ... }
    
    Task<Response> PerformSomeAction<Response, Request>(
                        Request request, string token) 
                        where Response : ResponseModel
                        where Request : RequestModel { ... }
}

Also just for fun: the compiler will let you overload like this (in general), as the signature is fundamentally different:

static Task<U> PerformSomeAction<T, U>(
   T request, string token)  { ... }

static Task<U> PerformSomeAction<U, T>(
   T request, string token)  { ... }

But not this, as the signature is essentially the same (if you could it would raise all sorts of strange overload resolution issues):

static Task<U> PerformSomeAction<T, U>(
   T request, string token)  { ... }

static Task<U1> PerformSomeAction<T1, U1>(
   T1 request, string token)  { ... }

Upvotes: 1

Related Questions