Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top