C# Error CS1946 – An anonymous method expression cannot be converted to an expression tree

C# Error

CS1946 – An anonymous method expression cannot be converted to an expression tree

Reason for the Error & Solution

An anonymous method expression cannot be converted to an expression tree.

An represents a set of statements but an expression tree must not contain a statement. Therefore an anonymous method cannot be represented by an expression tree.

To correct this error, change the anonymous method to a .

Example

The following example generates CS1946:

// cs1946.cs  
using System;  
    using System.Linq.Expressions;  
  
    public delegate void D();  
  
    class Test  
    {  
        static void Main()  
        {  
            Expression<D> tree = delegate() { }; //CS1946  
            // Try using a lambda expression instead.  
            // Expression<D> tree = (x) => x + 1;  
        }  
    }