简体   繁体   中英

C# 6 null conditional operator does not work for LINQ query

I expected this to work, but apparently the way the IL generates, it throws NullReferenceException . Why can't the compiler generate similar code for queries?

In the ThisWorks case, the compiler generates code that short circuits the rest of the expression, why can't it do the same thing for LINQ query case?

class Target
{
    public ChildTarget Child;
}

class ChildTarget
{
    public int[] Values;
}

IEnumerable<int> ThisWorks(Target target) =>
    target.Child?.Values.Select(x => x);

IEnumerable<int> ThisDoesNotWork(Target target) =>
    from x in target.Child?.Values select x;

ThisWorks(new Target());
ThisDoesNotWork(new Target()); // this throws NullReferenceException

Decompiled results

private static IEnumerable<int> ThisDoesNotWork(Target target)
{
    ChildTarget child = target.Child;
    IEnumerable<int> values = (child != null) ? child.Values : null;
    Func<int, int> func;
    if ((func = Program._func) == null)
    {
        func = (Program._func = new Func<int, int>(Program._funcMethod));
    }
    return values.Select(func);
}

private static IEnumerable<int> ThisWorks(Target target)
{
    ChildTarget child = target.Child;
    IEnumerable<int> values;
    if (child == null)
    {
        values = null;
    }
    else
    {
        IEnumerable<int> values = child.Values;
        Func<int, int> func;
        if ((func = Program._func2) == null)
        {
            func = (Program._func2= new Func<int, int>(Program._funcMethod2));
        }
        values = values.Select(func);
    }
    return values;
}

The answer is in the C# language specification, which says

A query expression of the form

from x in e select x

is translated into

( e ) . Select ( x => x )

Note the parentheses around e in the last line. That shows clearly that the null-conditional expression (in your example) ends before Select is called, which means Select might be called with the resulting null.

Why can't it do the same thing for Linq? Because that's not the way the feature was designed to work. The specification for the null-conditional operators do not have a special case for queries, nor vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM