C# – params T[] vs IEnumerable as parameter type

apiapi-designc

I know there's a proposal for params IEnumerable<T>.

When designing an API, when should we choose params T[] (params array) over IEnumerable<T>. Or should both be implemented for better end-user experience?

Example:

void MyCoolMethod(params string[] strings)

void MyCoolMethod(IEnumerable<string> strings)

When using params invocation is greatly simplified, but then if you want to pass some IEnumerable then you have to call ToArray.

Best Answer

The params keyword is only useful, when you as the coder will pass a number of strings that can vary between calls and you don't want to put them into an array manually for every call.

The IEnumerable<T> data type is useful, when you as a coder have a collection of any type and want to pass it.

So tailor your method to your audience. Those string you pass, do they come as hardcoded string from the developer? Like .Allow("GET", "PUT", "POST") or do they come from a different routine in your program like .Allow(this.ReadAllowedVerbsFromConfiguration())?

When the human sitting in front of the machine has to type out the parameters, use params, otherwise an IEnumerable<T> might be the better choice.

Related Topic