Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Note: This blog has moved to omervk.wordpress.com.

Omer van Kloeten's Facebook profile

Omer has been professionally developing applications over the past 8 years, both at the IDF’s IT corps and later at the Sela Technology Center, but has had the programming bug ever since he can remember himself.
As a senior developer at NuConomy, a leading web analytics and advertising startup, he leads a wide range of technologies for its flagship products.

Get Firefox


powered by Dapper 

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

Linq: FirstOrFallback

Sometimes you want to use FirstOrDefault, but the default value of T is a valid value that might get returned. If you used FirstOrDefault, you wouldn't know whether the value that you got is a valid first or the default fallback. I use FirstOrFallback to explicitly specify which fallback value I want, rather than always use default(T):

public static T FirstOrFallback<T>(this IEnumerable<T> enumeration, T fallback)
{
    // Check to see that enumeration is not null
    if (enumeration == null)
        throw new ArgumentNullException("enumeration");

    IEnumerator<T> enumerator = enumeration.GetEnumerator();

    enumerator.Reset();

    if (enumerator.MoveNext())
        return enumerator.Current;

    return fallback;
}

On a side note: I realize most of the extension methods I post here are pretty obvious, but I love sharing time-saving code. :)

Comments

No Comments