-1

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....
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

-2

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();
    }
}
-3
public async Task<OrderDto> ExecuteOrderOperations<T>(T request, CancellationToken cancellationToken, Domain.Entities.FoodBusiness foodBusiness)
{
    // code....
}
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
Pravin007
  • 35
  • 1