Since Javascript is the language that I am the most proficient at, I am familiar with using functions as first-class objects. I had thought that C# lacked this feature, but then I heard about Func
and Action
and delegate
, which I think are pretty awesomesauce.
For example, you can declare a Func
that concatenates two strings and puts a space between them like this:
Func<string, string, string> concat = (a,b) => a + " " + b;
I noticed that when you type
Func<
the IntelliSense shows that it has 17 overloads:
delegate System.Func<out TResult> delegate System.Func<in T, out TResult> delegate System.Func<in T1, in T2, out TResult> ...snip... delegate System.Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>
That made me laugh. I looked at the MSDN docs for Func
and laughed again. This made me try to declare a Func
with 17 arguments. It causes an error (Using the generic type 'System.Func<TResult>' requires 1 type arguments
).
I can agree that it's probably not a good idea to have a Func
that accepts more than 16 arguments. Even so, this seems like a kludgy way for Func
to be implemented. It requires 17 trivially different overloads to be documented. This is all it really should need to know: the last type parameter is the return type, and all the type parameters before it are the argument types.
So what could I do if I wanted to create a Func
with more than 16 parameters? Why is there a limit anyway? Why can't C# just let you declare a Func
with an arbitrary number of arguments?
Functions with three arguments (triadic function) should be avoided if possible. More than three arguments (polyadic function) are only for very specific cases and then shouldn't be used anyway.
Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.
This limit is determined by stacked frame size, which is set by OS. Theoretically you can set these max stack size to 8192 bits. Each variable takes up 32 bits then you could pass 256 parameters.
You're hoping for something like variadic type arguments which C# lacks. C# requires the arity of generic types to be fixed, therefore the heinous proliferation of Func
, Action
, and Tuple
types.
If you're language shopping, this feature was added in C++11, but you should probably just use jQuery. :-)
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