Max
Max

Reputation: 4405

Does the params keyword guarantee items to be in the same order as they are listed?

I'm working on a simple API that will accept a number of IBehaviours which are then applied in configuration. I am designing this using the params keyword since often there is just one behaviour wanted, but sometimes more.

However, it is very important that behaviours are applied in the correct order.

public void Configure(string wow, params IBehaviour[] behaviours) { ... }

Configure("oh yes", new MustHappenFirst(), new MustHappenSecondly());

Does this

  1. Technically imply that behaviours occurs in the same order when enumerating? (as in standard-wise, not simply practically-wise).

  2. Semantically and intuitively convey that same behaviour?

Thanks.

Upvotes: 3

Views: 337

Answers (4)

Eric Lippert
Eric Lippert

Reputation: 660407

The evaluation of the arguments will happen in left-to-right order and they'll be put into the array in that order.

Note that if "null" is a valid value for a behaviour, you can get into trouble:

Configure("hello", null);

calls

Configure("hello", (IBehaviour[]) null);

not

Configure("hello", new IBehaviour[1] { null } );

so be careful with that.

Upvotes: 8

KeithS
KeithS

Reputation: 71593

Yes. Parameters specified for a method using the params keyword will be placed in the params array in the order they are specified in the method call. This is generally understood to be so by developers, who are familiar with params-using methods like String.Format where the order of a formatting value in the parameter list is very important.

Upvotes: 1

SLaks
SLaks

Reputation: 887867

  1. Yes; order is preserved.

  2. Yes; this is fine.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564731

Yes. When you use params, the compiler just turns the arguments into an array, in the same order that the arguments were listed in the program. They will always be in this order inside the method.

A call to:

Configure("wow", one, two, three);

Will always map to:

Configure("wow", new[] {one, two, three});

Upvotes: 4

Related Questions