Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing different number of arguments to a params method at runtime

Tags:

c#

I have method with params object[] args and would like to pass parameters at runtime depending on condition. It can be zero objects or one, two objects parameters.

How to build params object[] args at runtime?

like image 929
Tomas Avatar asked Oct 27 '25 21:10

Tomas


2 Answers

The simplest way would be populating a List<object> with the arguments that you would like to pass, and then calling ToArray() on it before the call to your vararg method. List<T> can grow dynamically, letting you accommodate as many params as you need. Here is a hypothetical example that passes an array with seven arguments:

var args = new List<object>();
args.Add(firstArg);
args.Add(secondArg);
for (int i = 0 ; i != 5 ; i++) {
    args.Add(i);
}
MyMethodWithVarArgs(args.ToArray());
like image 92
Sergey Kalinichenko Avatar answered Oct 30 '25 12:10

Sergey Kalinichenko


Use a simple object-array...

For example, a method with this signature

public void DoSomething(params object[] args)

can be called like this

object[] args = new object[] {"Hello", "World", 123};
DoSomething(args);

An array can be built easily at runtime (for example, using a List).

like image 25
Matten Avatar answered Oct 30 '25 12:10

Matten