C# Error CS1945 – An expression tree may not contain an anonymous method expression

C# Error

CS1945 – An expression tree may not contain an anonymous method expression

Reason for the Error & Solution

An expression tree may not contain an anonymous method expression.

Expression trees can only contain expressions. Anonymous methods can only represent statements.

To correct this error

  1. Do not try to create an expression tree with a statement.

Example

The following code generates CS1945:

// cs1945.cs  
using System;  
using System.Linq.Expressions;  
  
public delegate void D();  
class Test  
{  
    static void Main()  
    {  
        Expression<Func<int, Func<int, bool>>> tree = (x => delegate(int i) { return true; }); // CS1945  
    }  
}