[C#] I wish I knew : Nullable<T>.GetDefaultValue(T)
I’ve been a professional C# developer for years now, but I’m still discovering trivial stuffs. In “I wish I knew”, I describe a feature that I missed.
Given the following:
struct T {}
T? nullable;
T fallback;
I always though the only alternative to this:
T value = nullable.HasValue ? nullable.Value : fallback;
was this:
T value = nullabe ?? fallback;
But it turns out, you can also do this:
T value = nullabe.GetValueOrDefault(fallback);
Well… I’m not sure I’m really gonna use it but it made me realize how much I wish these LINQ extension methods exist:
ElementAtOrDefault<TSource>(this IEnumerable<TSource> source, TSource fallback);
FirstOrDefault<TSource>(this IEnumerable<TSource> source, TSource fallback);
LastOrDefault<TSource>(this IEnumerable<TSource> source, TSource fallback);
SingleOrDefault<TSource>(this IEnumerable<TSource> source, TSource fallback);