1

when I write a function with a generic like this

Task<ResultModel<bool>> CancelScheduledTask<T>(string scheduledTaskId, int year, int week) where T : TaskModel;

You have to provide the generic, because it can't be derived from the parameters

    switch (TaskType)
    {
        case Schedule.ROUTINE:
            cancelRoutineResult = await _taskRepository.CancelScheduledTask<RoutineTask>(TaskId, Year, Week);
            break;

        case Schedule.EVENT:
            cancelRoutineResult = await _taskRepository.CancelScheduledTask<EventTask>(TaskId, Year, Week);
            break;
    }  

Would it be possible to write this without the switch of an if else statement? something like this example which doesn't work

await _taskRepository.CancelScheduledTask<TaskType.TypeOfTask()>(TaskId, Year, Week);

public static Type TypeOfTask(this string taskType)
    {
        switch (taskType)
        {
            case Schedule.ROUTINE:
                return typeof(ScheduledRoutineModel);

            case Schedule.EVENT:
                return typeof(ScheduledEvent);

            default:
                return null;
        }
    }
Jiren
  • 536
  • 7
  • 24
  • 2
    You can do that with [reflection](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) but basically that's it. And for described use case using would be an overkill. – Guru Stron Jul 02 '22 at 11:35
  • @GuruStron maybe overcome it with use of [Fast Invoke](https://stackoverflow.com/a/17669142/2820150). Is this possible? – novice in DotNet Jul 02 '22 at 12:27
  • 1
    @noviceinDotNet while it can solve performance issues still for the provided code this is an overkill. – Guru Stron Jul 02 '22 at 12:29
  • 1
    I would ask why you need the generic type, why isn't your `TaskId` enough? Or even better, why are you calling that monstrosity instead of just using a normal `IDisposable` in the first place? – Blindy Jul 02 '22 at 13:36

1 Answers1

0

If not performance dependent,

MethodInfo methodInfo = _taskRepository.GetType().GetMethod("CancelScheduledTask").MakeGenericMethod(TaskType.TypeOfTask());
await (methodInfo.Invoke(_taskRepository, new[] { TaskId, Year, Week }) as Task<ResultModel<bool>>);
novice in DotNet
  • 771
  • 1
  • 9
  • 21