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]]
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With