I came across the beautiful Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult>
delegate in C# .NET 4.5 today. I assume 16 was an arbitrary place to stop (what methods have more than 16 parameters?) but it got me thinking: is it possible in C# to specify that a generic type can have any number of type arguments? in a similar way that the params keyword for methods allows for any number of arguments for a method. Something like this:
public class MyInfiniteGenericType<params T[]> { ... }
where inside the class you could then access the type arguments by enumerating through them or using T[index]
in the same way that params
allows within methods.
I've never had a use for this personally, but the Func delegate would be a perfect place to use it. There would be no need for 16 different types of Func!
So my question is, can this be done in any way in C#, and if not is this a silly idea?
By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
The "params" keyword in C# allows a method to accept a variable number of arguments. C# params works as an array of objects. By using params keyword in a method argument definition, we can pass a number of arguments. Note: There can't be anymore parameters after a params.
Params is an important keyword in C#. It is used as a parameter which can take the variable number of arguments. Important Point About Params Keyword : It is useful when programmer don't have any prior knowledge about the number of parameters to be used.
In C#, params is a keyword which is used to specify a parameter that takes variable number of arguments. It is useful when we don't know the number of arguments prior. Only one params keyword is allowed and no additional parameter is permitted after params keyword in a function declaration.
is it possible in C# to specify that a generic type can have any number of type arguments?
No, C# doesn't have anything like that I'm afraid.
Fundamentally Func<T>
and Func<T1, T2>
are entirely unrelated types as far as the CLR is concerned, and there's nothing like params
to specify multiple type arguments.
As for its utility: I can see cases where it could be useful, but I suspect they're rare enough to mean the feature doesn't cross the "benefit/cost" threshold. (Note that it would almost certainly require CLR changes too.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With