Tuesday, 16 July 2013

Non-obvious behaviour in the C# compiler with params array

I recently changed a function I was using inside a test, to take a params string[] parameter instead of a plain string[].

The change of behaviour surprised me at first, although after tracing the exception I could see why it happened.

Here’s an example (inside a test class, using NUnit and FluentAssertions)


private static int HowManyStrings(params string[] y)
{
return y.Length;
}

[Test]
public void TestHowManyStrings()
{
HowManyStrings("foo", "bar").Should().Be(2);
HowManyStrings("foo").Should().Be(1);

string myNullString = null;
HowManyStrings(myNullString).Should().Be(1);
HowManyStrings(default(string)).Should().Be(1);
HowManyStrings(null).Should().Be(1);
}


The last test causes an exception, because it’s OK to pass a string[] as the parameter, and the null (of unknown type) matches the string[] better than making a string[] { null } out of it.



It does feel like passing an untyped null to a params array parameter should produce a warning, either in the compiler or something like ReSharper – but neither flagged it up (C#5, ReSharper 7).