You can't use an open generic type as a generic type parameter, however, you can use a specific type S<T>
as a parameter:
public static R PerformOperationOnGenericArray<T,R>
(IList<T> myList, FunctionForGenericArray<T> operation)
where R : S<T>
In your case, if the type S
is a fully defined (closed type) at compiled time, you don't even need to do that:
public static S<T> PerformOperationOnGenericArray<T>
(IList<T> myList, FunctionForGenericArray<T> operation)
should be sufficient.
You only need to use the first form if S
itself will vary. So what do I mean by this. Let's look at an example. If you have:
class Foo<T> { }
you can write:
public static Foo<T> PerformOperationOnGenericArray<T>
(IList<T> myList, FunctionForGenericArray<T> operation)
But, if you have some group of related generic types:
class Foo<T> { }
class Bar<T> : Foo<T> { }
class Baz<T> : Foo<T> { }
and you want to allow the caller to specify which one to use, then you need to make the return type part of the generic signature of the method:
public static R PerformOperationOnGenericArray<T,R>
(IList<T> myList, FunctionForGenericArray<T> operation)
where R : Foo<T>
where callers will now need to specify the type of R
explicitly:
PerformOperationOnGenericArray<T,Bar<T>>( ... )
If you want to allow any generic type that accepts a single parameter to be allowed, there you are out of luck. The type system doesn't provide a way to express the restriction:
allow any generic type that allows a single parameter, and enforce that parameter to be a T
The best you can do is to define a well known interface that all known types conform to (like IEnumerable<T>
, or one you craft yourself), and use that as part of the generic constraint:
public static R PerformOperationOnGenericArray<T,R>
(IList<T> myList, FunctionForGenericArray<T> operation)
where R : IEnumerable<T>
However, in this case, the types supplied must all implement this interface. If you're looking for the former (where you can specify any type that just has to match on the number of type parameters) you're looking for generic duck typing(1) - which C# doesn't support.
An interesting side note on this. Creating a generic method whose types cannot be inferred by the compiler solely from the formal parameters of the method is something to try to avoid. When the parameters cannot be inferred, the caller is forced to specify all of the type parameters - which leads to confusing and verbose code. While sometimes these situations do come up, you're better off trying to avoid them, where possible.
(1) - C# does support duck typing in anonymous types within a single assembly if the types match in the order, types, and names of their members - upon which the compiler will assume that they are the same type.