Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named Parameters and the params keyword in C# [duplicate]

I have a C# method with a variable length argument list declared using the params keyword:

public void VariableLengthParameterFunction (object firstParam, 
                                             params object[] secondParam)

Is there any way of using named parameters when calling the method?

like image 471
marosoaie Avatar asked Apr 24 '13 13:04

marosoaie


People also ask

What is the params keyword?

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

What is params in C?

The parameter in C refers to any declaration of variables within the parenthesis during the function declaration. These are listed in the function's definition, separated by commas. Example of Parameter. int add (int a, int b) { int c = a + b; return c; }

What are params used for?

A parameter is a special kind of variable in computer programming language that is used to pass information between functions or procedures. The actual information passed is called an argument.

What does params in C# mean?

The "params" keyword in C# allows a method to accept a variable number of arguments. C# params works as an array of objects. By using params keyword in a method argument definition, we can pass a number of arguments.


2 Answers

You can call it using named parameter like this:

VariableLengthParameterFunction(
    secondParam: new object[] { 5, 7, 3, 2 }, 
    firstParam: 4);
like image 123
Hossein Narimani Rad Avatar answered Oct 05 '22 23:10

Hossein Narimani Rad


EDIT: I assumed you want to access the params object[] secondParam array using named parameters.

Currently only the code inside the method knows what secondParam may contain. From just the method signature there's no link between the object[] and names/types for each element within that array.

Furthermore, since you're using the params keyword, there is no way of supplying secondParam[1] without supplying a value for secondParam[0] (or null).

Perhaps you could create an overload which takes named parameters, and which creates the object[] and then calls this method. Or the other way around.

like image 44
C.Evenhuis Avatar answered Oct 06 '22 01:10

C.Evenhuis