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?

Était-ce utile?

La 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.

Autres conseils

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top