19

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?

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
marosoaie
  • 2,352
  • 23
  • 32

2 Answers2

35

You can call it using named parameter like this:

VariableLengthParameterFunction(
    secondParam: new object[] { 5, 7, 3, 2 }, 
    firstParam: 4);
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
  • This doesn't seem to work with msbuild tools 2015, the secondparam is lost if you use the shorthand for a single element? (works with devenv though) – Oskar Duveborn May 25 '16 at 14:45
1

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.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • that's a good point , but using the ``` params ``` keyword we already know there will be just a bunch of input with no special order , so it wouldn't be necessary. – PayamB. Nov 11 '20 at 22:12