user2341923
user2341923

Reputation: 4727

Named arguments call in C# with variable parameter number

Suppose I have the following C# function:

void Foo(int bar, params string[] parpar) { }

I want to call this function using named arguments:

Foo(bar: 5, parpar: "a", "b", "c");

The compiler gives error message: “Named arguments cannot precede positional” since I have no name before “b” and “c”.

Is there any way to use named arguments without manually representing params as an array?

Upvotes: 7

Views: 3990

Answers (2)

drobison
drobison

Reputation: 908

Adding this in case someone lands here from google like I did. You will also receive this error when you have not explicitly named all your parameters and all your explictly named parameters are not at the end.

void Foo( int parameterOne, int parameterTwo, int parameterThree) {};

// throws Named Arguments cannot precede positional
Foo(parameterOne: 1, parameterTwo:2, 3);

//This is okay
Foo(1, parameterTwo:2, parameterThree:3);

Upvotes: 7

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

No, there is no syntactic sugar to make variable arguments named except explicitly specifying array.

Note that params arguments would need to be individually named if such syntax would be allowed (to see where positioned argument ends), but there is only one name.

Upvotes: 9

Related Questions