While working with Linq extensions it's normal to see code like this:
IEnumerable<int> enumerable = GetEnumerable();
int sum = 0;
if (enumerable != null)
{
sum = enumerable.Sum();
}
In order to enhance the code quality, I wrote the following extension method that checks for nullable enumerables and breaks the linq execution.
public static IEnumerable<T> IgnoreIfEmpty<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null) yield break;
foreach (var item in enumerable)
{
yield return item;
}
}
So, I can refactor the code to be like this:
var sum = GetEnumerable().IgnoreIfEmpty().Sum();
My questions now:
- What penalties are associated with my extension method at runtime?
- Is it's a good practice to extend linq that way?
Update: My target framework is: 3.5