Working around null values in LINQ queries

I’m almost ashamed to admit I hadn’t commonly used the ‘null coalescing operator‘ ?? in C# until recently, and was commonly writing code like

var myVar = myNullableVar == null ? myNullableVar.Value : 0;

or variations on a theme using HasValue etc (still better than the long-hand if-else mind you)

Clearly this is more readable as

var myVar == myNullableVar ?? 0;

Often I find that things break down when you introduce Entity Framework, as there’s limitations on what it will understand (from the point of view of translating to the underlying data context).  Null values though are another place you can save a bit of repetitive code, as you’ll quite often have nullable dates, or other nullable types..

var output = (
    from tab in context.MyTable
    where tab.EffectiveDate == effectiveDate
    select new 
        Code = tab.Code,
        /* Old
        Value = tab.Value == null ? 0 : tab.Value.Value
        // New
        Value = tab ?? 0

This is a pretty simple example, but in conjunction with the SqlFunctions library, you can keep things nice and neat with type conversions in your code.

It’s only when you look a little further into the language that you see c#’s got quite a nice set of operators now 🙂