Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 847
user2341923 Avatar asked Sep 14 '13 07:09

user2341923


People also ask

What are called arguments in C?

The values that are declared within a function when the function is called are known as an argument. The variables that are defined when the function is declared are known as parameters. 2. These are used in function call statements to send value from the calling function to the receiving function.

Does C++ support named parameters?

The Wikipedia page about named parameters tells that C++ doesn't support it.

What are the arguments in this function call?

Arguments are the values passed from a function call (i.e., they are the values appearing inside the parentheses of the call) and are sent into the function). The following example is based on pass-by-value, the most common and familiar argument passing technique.

What is call by reference in C?

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.


2 Answers

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.

like image 58
Alexei Levenkov Avatar answered Oct 17 '22 03:10

Alexei Levenkov


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);
like image 22
drobison Avatar answered Oct 17 '22 04:10

drobison