Thursday, April 16, 2009

my solution to Eric Lippert's quiz

Eric posted a quiz a few days ago, it generated quite a number of responses, so I thought I would answer with the shortest possible C# answer (with my previous team we used to kinda compete on refactoring), so here it is (Justin and Paul, bring it on!):
The problem:
Write me a function that takes a non-null IEnumerable and returns a string with the following characteristics:

(1) If the sequence is empty then the resulting string is "{}".
(2) If the sequence is a single item "ABC" then the resulting string is "{ABC}".
(3) If the sequence is the two item sequence "ABC", "DEF" then the resulting string is "{ABC and DEF}".
(4) If the sequence has more than two items, say, "ABC", "DEF", "G", "H" then the resulting string is "{ABC, DEF, G and H}". (Note: no Oxford comma!)

My solution:

static string JoinStrings(IEnumerable<string> strings) {

int len = strings.Count();

return "{"+(

(len > 1) ?

strings.Take(len - 1)

.Aggregate((string head, string tail) => head+", "+tail)+

" and " +strings.Last()

: (len == 1) ?


: "")+



Thursday, April 02, 2009

public ASP.NET MVC { get; private set; }

For the 2 people who don't read many blogs (or twitter), but do read this one, yesterday it was announced that ASP.NET MVC 1.0 is open source baby! "Free like Speech." and there are no restrictions to the platform either, the license is MS-PL which provides broad rights to modify and redistribute the source code.

The first question that was raised was "can I submit patches?" and the answer is no, however nothing stops you from going and creating your own copy (forking) and start modifying it and redistributing it like this guy has already done.

You can get the source code here.

Did you know? Interface members are allowed to be private

This one comes as a surprise to most people, but it is possible to have a private implementation for an interface member, let's look at a very simple example, just for purposes of the ilustration.

public interface ITest {

void Test();


public class Test : ITest {

void ITest.Test() {



public void Test2() {




class Program {

static void Main(string[] args) {

ITest t = new Test();


Test t2 = new Test();

//t2.Test(); //<<=== doesn't compile

If you don't believe it you can try it of course.

But why is this useful or how do you use this?

The technique allows you to ensure that the method is only visible to those who are using a variable of the interface type. All this does is to force the use of the member through an instance of the interface, meaning, for this example, if you want to get access to the .Test method, you can only do so through a variable of type ITest.

The only trick to make this work is to precede the member declaration with the Interface type as in:

void ITest.Test();

Not the most useful of tricks, but something to have on the bag of tricks, or maybe something to make you win a bet ;)