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  
    }  
}  

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...