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

The Wildhearts Fishing For Luckies lenticular CD cover

Apropos of nothing…

My copy of “Fishing For Luckies” by The Wildhearts has a lenticular cover that flicks between two pictures. I decided to make an animated gif that alternates between the two to use as the cover art when I ripped it. Whether anything renders the animation is a different matter, but just so I never have to do it again, I’m recording the image here.

Fishing

I scanned the inlay at 300dpi and then wrote some code to split the image into odd and even sets of (3-line-high) blocks, repeating each row twice. I then saved out the two images formed from the odd and even sets and used UnFREEz to make the animated gif.

Anyway, it’s a good album and you can buy it with the lenticular cover, or with a normal cover but with bonus disc, or ready-ripped but with some static cover art .

Thursday, 11 July 2013

Checkboxes Beside Labels in ASP.Net MVC4

This had me stumped for a while, so here’s what you need to do:

Inside your form,

<li>
@Html.CheckBoxFor(m => m.XX)
@Html.LabelFor(m => m.XX, new {@class="checkbox"})
</li>


This is for a boolean XX in the model, marked with the appropriate attributes to get the label text. The important thing is the class attribute for the label, because that applies the style defined in the default css:



label.checkbox { display: inline;}



To make it appear on the same line as the checkbox itself.