Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Forward variable length arguments

Tags:

c#

I know how to declare variable length parameter lists using keyword params. But how about when you want to pass those variable length arguments to another function. For example :

public static void Main() {
    varargs_m1(1,2,3,4);
}

public static void varargs_m1(params object[] args) {
    varargs_m2(args);      // Writes args.Length = 4
    varargs_m2(0, args);   // Writes args.Length = 2 
                           // args = [0, [1,2,3,4]] 
}

public static void varargs_m2(params object[] args) {
    Console.WriteLine("args.Length = " + args.Length);
}

When I call varargs_m2(0, args) how can I get the arguments to be [0,1,2,3,4] instead of [0, [1,2,3,4]]

like image 407
Candide Guevara Marino Avatar asked Mar 28 '26 22:03

Candide Guevara Marino


1 Answers

You could concatenate your a new array containing {0} with your existing array and then pass that along using the LINQ Concat() method:

public static void varargs_m1(params object[] args) 
{
    varargs_m2(new object[]{0}.Concat(args).ToArray());
}

If you wanted to avoid using LINQ entirely, you could simply create a new array and handle it that way as well :

public static void varargs_m1(params object[] args) 
{
    // Your new values
    var newValues = new object[]{ 0 };
    // Build a new array 
    var combined = new object[newValues.Length + args.Length];
    // Copy each of your values into the new array
    newValues.CopyTo(combined, 0);
    args.CopyTo(combined, newValues.Length);
    // Pass your new values along
    varargs_m2(combined);
}
like image 53
Rion Williams Avatar answered Apr 02 '26 20:04

Rion Williams