I’m working on a generic method that accepts parameters whose types should be inferred from the generic type arguments of a given interface. I’d like to achieve compile-time type safety similar to the following (non-compiling) code:
/// <summary>
/// Applies the specified IOperation to this PradResult.
/// </summary>
/// <typeparam name="T">The type of the operation to apply.</typeparam>
/// <param name="p1">The first parameter for the operation.</param>
/// <param name="p2">The second parameter for the operation.</param>
/// <param name="parameters">Additional parameters for the operation.</param>
/// <returns>A new PradResult after applying the operation.</returns>
public PradResult Then<T>(T.Args[0] p1, T.Args[1] p2, params object[] parameters)
where T : IPradOperation<,>, new()
{
var opType = typeof(T);
IOperation op = (IOperation)Activator.CreateInstance(opType);
var forwardMethod = opType.GetMethod("Forward");
var forwardParams = parameters.Prepend(p2).Prepend(p1);
var length = parameters.Length;
...
}
The idea is that the p1 and p2 parameters should automatically have their types inferred based on the first and second generic type arguments of the IPradOperation interface implemented by T.
However, I understand that C# doesn’t currently support this syntax directly. Are there any workarounds or alternative patterns I can use to achieve this kind of compile-time type inference in my generic method?
I want the Then method to be as user-friendly as possible so that they don’t have to specify the types of ‘T.Args[0]’ and ‘T.Args[1]’, which in my example would be of type ‘Matrix’.