A previous question discusses IEnumerable and the convention of using empty collections instead of null valued ones. It is a good practice as it does away with many mistake-prone null checks.
But the answers don't quite address one of the cases. Many times I'm forced to deal with null values, specifically when arrays are returned from foreign methods. An example:
(foreignObj.GetPeople() ?? Enumerable.Empty<Person>())
.Where(p => p.Name != "John")
.OrderBy(p => p.Name)
.Take(4);
I've written a helper method which does improve readability somewhat.
public class SafeEnumerable
{
public static IEnumerable<T> From<T>(T[] arr)
{
return arr ?? Enumerable.Empty<T>();
}
}
Resulting in:
SafeEnumerable.From(foreignObj.GetPeople())
.Where(p => p.Name != "John")
.OrderBy(p => p.Name)
.Take(4);
I don't mind this, but I'm looking for better ideas. It seems like I'm adding something that should be there already.