Here’s a pattern that I’ve seen occur a number of times - a pair of method overloads, one accepting IEnumerable<T> and the other accepting params T[].

void Process(IEnumerable<string> commandline) { ... }
void Process(params string[] parameters) { ... }

Often, the params edition is provided as a convenience overload, making the API simpler for consumers. The implementation is usually a simple delegation call to the main method:

void Process(params string[] parameters)

There’s a trap here though - as shown, you’ll get a Stack Overflow exception thrown in good order.

The reason is simple - but perhaps not obvious. When the compiler is matching method signatures to work out which version of Process() to invoke, there’s a better match with string[] than with IEnumerable<string>, so the generated code goes into a tight loop.

The solution is to cast parameters to the more general type so that there is only one viable match:

void Process(params string[] parameters)
    Process( (IEnumerable<string>) parameters );

The way that the compiler selects which overload to call is entirely predictable, but complex, and sometimes gives unexpected results. It’s worth learning enough about the process to be able to troubleshoot problems (like this one). That said, if your specific problem is too complex, the best answer might be to rename some of the overloads so that a future maintainer doesn’t have the same problem to face.


blog comments powered by Disqus
Next Post
Doing less with LINQ  30 Jun 2010
Prior Post
NAntGraph v2.2 Released  16 Jun 2010
Related Posts
The Liskov substitution principle goes both ways  21 Mar 2020
Avoid hardcoded wait times  26 May 2018
Guaranteed Progression  19 May 2018
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
More smart-code posts »
June 2010