How to use my method with differents parameters with generics type?

65 Views Asked by At

I have two methods with same code inside and with different param types. How to use one generic method without duplicate method in C# and ASP.NET Core?

My method1:

public async Task<OrderDto> ExecuteOrderOperations(CreateOrderCommand request, CancellationToken cancellationToken, Domain.Entities.FoodBusiness foodBusiness)
{
    // code....
}

My method 2 :

public async Task<OrderDto> ExecuteOrderOperationsForSH(CreateOrderCommandSH request, CancellationToken cancellationToken, Domain.Entities.FoodBusiness foodBusiness)
{
    // same code....
}
2

There are 2 best solutions below

5
Pravin007 On
public async Task<OrderDto> ExecuteOrderOperations<T>(T request, CancellationToken cancellationToken, Domain.Entities.FoodBusiness foodBusiness)
{
    // code....
}
0
TacticalCamel On

If CreateOrderCommand and CreateOrderCommandSH looks similar, I suggest extracting their common functionalities to a base class or interface.
Then you can call the method with both types by changing the parameter to be the inherited type:

public async Task<OrderDto> ExecuteOrderOperations(CreateOrderBase request, CancellationToken cancellationToken, Domain.Entities.FoodBusiness foodBusiness)
{
    //code...
}

If this is not possible, you can't do much else than an ugly workaround which I would not recommend.
You could only apply 1 class type constraint for a generic parameter, so ensuring T is really one of those 2 classes is not possible at compile time.
Your only remaining solution is to type check in the method body:

public async Task<OrderDto> ExecuteOrderOperations<T>(T request, CancellationToken cancellationToken, Domain.Entities.FoodBusiness foodBusiness)
{
    switch(request)
    {
        case CreateOrderCommand command:
            //code...
            break;
        case CreateOrderCommandSH commandSH:
            //code...
            break;
        default:
            throw new ArgumentException();
    }
}