Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C# only allows the last parameter to be of "params type"

While researching this I found this question: Why C# allows that only the last parameter of a method is of "variable length"

While I 100% agree with the answers there and understand the rules of allowing such thing would be horrifyingly complicated as stated there, it hasn't provided me with an answer to my actual question. The linked question talks about T f(params A[] a, params B[] b), so multiple arguments with the params keyword.

But there is no mention whatsoever of the following idea:

void Foo(int head, params int[] body, int tail)

Or to be specific: Instead of asking why you can't have multiple params arguments, why can't we have a single params argument, but just not at the end (either somewhere in the middle, or at the beginning)?

I cannot think of a single reason why that would be complicated, but please prove me wrong!

For example lets suppose the following function:

void Foo(int head, params int[] body, int tail)
{
    Console.WriteLine($"{head} [{string.Join(", ", body)}] {tail}");
}

I think there is no doubt about what the result should be.

Foo(1, 2)       // 1 [] 2
Foo(1, 2, 3)    // 1 [2] 3
Foo(1, 2, 3, 4) // 1 [2, 3] 4

There's no "How to determine where a ends and b begins then?" (top comment on the linked question) in this case so I don't see the problem.

like image 837
Olle Kelderman Avatar asked Mar 07 '23 22:03

Olle Kelderman


1 Answers

These functions :

void Foo(int a, params int[] b)
void Foo(int a, params int[] b, int c)
void Foo(params int[] a, int b)

have different signatures, so they should simply be allowed if you tell that params can be wherever you want.

But then you can't resolve which one to call if you have :

Foo(1, 2, 3);

I think it would be a "language specification smell" if you say : "you can use use params wherever you want, unless if at some point during the compilation there is an ambiguous call".


The goal of a high level language like C# to avoid ambiguousness and put developpers in good tracks. If you have to change completely the structure of your code, because you add a line of code and now some language feature is not available anymore, it's not going to help you.

So, yes, it would be possible, but I seriously doubt it would be helpful to developers globally.

It would complicate the rule "you can declare several time a function, as long as it is with different signatures"

It would also greatly increase the difficulty with linking to other assemblies.

like image 81
Pac0 Avatar answered Apr 27 '23 06:04

Pac0