0

I have a set of methods that accept type arguments:

public void Process<T>() { ... }
public void Process<T1, T2>() { ... }
public void Process<T1, T2, T3>() { ... }

Inside of these methods, I'm creating workers that execute sequentially, in the order specified by the type arguments, so for example:

public void Process<T1, T2>() {
    List<WorkerProcess> workers = GetWorkersFromTypes(typeof(T1), typeof(T2));
    if (workers?.Count > 0)
        foreach (var worker in workers)
            if (worker != null)
                worker.Process();
}
public List<WorkerProcess> GetWorkersFromTypes(params Type[] workerTypes) {
    var workers = new List<WorkerProcess>();
    foreach (var type in types) {
        if (type == typeof(WorkerA))
            workers.Add(new WorkerA());
        else if (type == typeof(WorkerB))
            workers.Add(new WorkerB());
    }

    return workers;
}

While this is effective, it's rather verbose using the typeof keyword. I'm wondering if there's something similar for type arguments that would enable something like this instead:

public void Process<T1, T2>() {
    List<WorkerProcess> workers = GetWorkersFromTypes<T1, T2>();
    ...
}
public List<WorkerProcess> GetWorkersFromTypes<params T[] types>() { ... }

In all my research, I'm coming to the conclusion that it is not possible, but there are much smarter and more effective researchers here that might be able to prove otherwise.


Is there a way to get infinite type arguments, in a manner similar to the params keyword, in C#?

Hazel へいぜる
  • 2,751
  • 1
  • 12
  • 44
  • 2
    I don't think so... https://referencesource.microsoft.com/#mscorlib/system/action.cs,81 – thepirat000 Jun 30 '21 at 23:37
  • 1
    Unfortunate this was closed since I was going to post this as an answer, you might be able to implement your requirement by getting the constructors of the passed types with Reflection - https://learn.microsoft.com/en-us/dotnet/api/system.type.getconstructor?view=net-5.0#System_Type_GetConstructor_System_Type___ – IllusiveBrian Jun 30 '21 at 23:48

0 Answers0