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()); I may be missing something, but why can't you simply call the method directly with the arguments you want, depending on the condition(s) that you mentioned? You don't need to put them into an array (unless you already have them in an array, but then you just pass the array...).
For example, given:
public static void Method(params object[] args) { } You can do:
if (condition1) { Method(); } else if (condition2) { Method("arg"); } else { Method("arg1", "arg2"); }