15 May 2009

Today I read Eric Lipert's blog latest entry. It is about the semantic difference between null and empty. An easy example is with Collections. An empty Collection is not the same as an non-existing (ie. null) Collection.

However, as mentioned, how may times did you wish that foreach statement would work on an null Collection? How convenient would it be!

So far, what I was doing was:

foreach (var item in list ?? new List<SomeType>())
{
    //Do Stuff...
}

But something nicer exists: Enumerable.Empty. Using that, the code becomes:

foreach (var item in list ?? Enumerable.Empty<SomeType>())
{
    //Do Stuff
}

It's actually longer, but it reads easier. The intent is quite obvious, I bet you can show this to someone who doesn't know about the null coalescing operator and he would get what it does! Unfortunately I'm now working on Java and my colleagues would burn me alive if they knew I secretly pledged allegiance to .NET...



blog comments powered by Disqus