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

1 comment:

  1. Great Article
    Cyber Security Projects

    projects for cse

    Networking Security Projects

    JavaScript Training in Chennai

    JavaScript Training in Chennai

    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete