4

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?

0

3 Answers 3

8

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()); 
Sign up to request clarification or add additional context in comments.

1 Comment

@Tomas: Do you not know that the parameters passed to the method are automatically combined by the compiler into an array? Call the method like MyMethodWithVarArgs(1,2,3,4,5,6) is the same as MyMethodWithVarArgs(new object[] {1,2,3,4,5,6}) only with less work.
5

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).

Comments

2

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"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.