When creating Wiretap, I needed to be able to sort a collection of Wiretap Servers in C# code. There's nothing wrong with the way I ended up doing, but it never sat very well with me. Using anonymous delegates, which are provided in C# 2.0, I can remove this niggling code smell.
My initial code looked a little something like this:
...
private class ServerComparer : IComparer<Server>
{
public int Compare(Server leftTestInstance, Server rightTestInstance)
{
return string.Compare(leftTestInstance.Name, rightTestInstance.Name);
}
}
public void List()
{
// Find all of the servers with a status of ok
List<Server> okServers = list.FindAll(StatusOk);
// Sort the collection in name ascending order
okServers.Sort(new ServerComparer());
}
...
This is ok, but I'm creating a whole new class for nothing really - it's never going to get reused and it sits in the same file as the outer class. It just doesn't feel right.
public void List()
{
// Find all of the servers with a status of ok
List<Server> okServers = list.FindAll(StatusOk);
okServers.Sort(delegate(Server leftServer, Server rightServer)
{
return string.Compare(leftServer.Name, rightServer.Name);
});
}
Better. The code's all in one place, and I don't need to create a new class any more. For those with an eye to the future, the next version of C# can potentially make things even neater. I think this type of code would work with C# 3.0 - I'm going to download a beta to try and check but I'd appreciate any feedback.
public void List()
{
// Find all of the servers with a status of ok
List<Server> okServers = list.FindAll(StatusOk);
okServers.Sort(leftServer, rightServer => string.Compare(leftServer.Name, rightServer.Name));
}
For me, we're approaching optimum sweetness right there. Thanks to Dan Wahlin, who inspired this post.