C# - Cannot use "is" operator in lambda expression
Asked Answered
F

1

16

I am using AgileMapper with this code:

source.Map().OnTo(target, (options) =>
  options.IgnoreSources((options) =>
    options.If((value) =>  value is null)
  )
);

However, the compiler is complaining:

An expression tree may not contain pattern-matching 'is' expression`

It works if I use value == null, but I want to understand why is not working?

Fraction answered 10/3, 2020 at 7:55 Comment(1)
Use ReferenceEquals(value, null); instead, which internally is the same.Sheathing
S
33

value is null uses the constant pattern. Pattern matching was introduced in C# 7, long after expression trees, and cannot (currently) be used in expression trees. It's possible that that will be implemented at some point, but at the moment it's invalid. Note that this is only for expression trees - not lambda expressions that are converted to delegates. For example:

using System;
using System.Linq.Expressions;

class Program
{
    static void Main()
    {
        object x = null;
        Func<bool> func = () => x is null; // Fine
        Expression<Func<bool>> expression = () => x is null; // CS8122
    }
}

There are various restrictions on code within expression trees. You can't use dynamic operations or tuple literals, for example. The restriction on pattern matching is just another example of this.

Santiagosantillan answered 10/3, 2020 at 7:59 Comment(2)
Hey Jon, is there any ongoing discussing to add support for this that you could link to? Any proposals in csharlang github or something like that?Clovis
@julealgon: Not that I'm aware of. I'd suggest asking on the GitHub repo.Santiagosantillan

© 2022 - 2024 — McMap. All rights reserved.