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?
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());
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).
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