Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Cannot use "is" operator in lambda expression

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?

like image 644
geeko Avatar asked Mar 10 '20 07:03

geeko


1 Answers

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.

like image 194
Jon Skeet Avatar answered Sep 30 '22 19:09

Jon Skeet