Sunday, June 05, 2011

C#/.NET Little Wonders: Empty(), DefaultIfEmpty(), and Count()

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders post can be found here.

On this post I will finish examining the System.Linq methods in the static class Enumerable by examining two extension methods Count() and DefaultIfEmpty(), and one static method Empty().

The Empty() static method

How many times have you had to return an empty collection from a method (either due to an error condition, or no items exist, etc.) and created an empty array or list?

Let’s look at a simple POCO to hold transfers between two bank accounts:

public class Transfer
{
public string FromAccount { get; set; }
public string ToAccount { get; set; }
public double Amount { get; set; }
}
Now let’s say we have a data access object that is supposed to grab the outstanding transfers and return them.  However, if the transfer service is down for maintenance, we just want to return an empty sequence of transfers.

We could of course return null, but returning the empty sequence is generally preferable than returning null.  So we’ll return an empty sequence in the form of a list (or array would do as well):

public class TransferDao
{
public IEnumerable<Transfer> GetPendingTransfers()
{
if (!_txfrService.IsInMaintenanceMode())
{
// create a list of transfers and return it...
}
// otherwise, since we're in maintenance mode, return an empty collection:
return new List<Transfer>(0);
}
}
Read more: James Michael Hare