Search code examples
c#linqnullreferenceexceptionnull-coalescing-operator

Null coalescing within an invocation chain


If I have a long list of objects that each has the possibility of returning null within a "Linq where" clause, e.g.

 SomeSource.Where(srcItem=>(srcItem.DataMembers["SomeText"].Connection.ConnectedTo as Type1).Handler.ForceInvocation == true));

the indexer can return null and the "as" operator may return null. It is possible that the object does not have a connection (ie. The property is null). If a null is encountered anywhere, I would like the where clause to return "false" for the item being evaluated. Instead, it aborts with a null reference exception.

It appears to me that this would be contrived to express within a single C# expression. I don't like to create a multi line statement or create a separate func for it. Is there some use of the null coalescing operator that I'm missing?


Solution

  • You're looking for the .? operator (or is it ?.—one of those, anyway), which does not exist in C# (though it is an often-requested feature, according to Eric Lippert).

    The only possible suggestion I have is to write a method that takes an expression and uses it to check for any nulls. But this will come at a performance cost. Anyway, it might look like:

    T TryOrDefault<T>(Expression<Func<T>> expression)
    {
        // Check every MemberExpression within expression one by one,
        // looking for any nulls along the way.
    
        // If a null is found, return default(T) or some default value.
    
        // Otherwise...
        Func<T> func = expression.Compile();
        return func();
    }