Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare Lambda Expression as a class constant field

Why isn't it possible to declare a class constant filed of type Lambda Expression. I want Something like this:

class MyClass
{
   public const Expression<Func<string,bool>> MyExpr = (string s) => s=="Hello!";
}

But I get the compile error: Expression cannot contain anonymous methods or lambda expressions

like image 939
Alireza Avatar asked Oct 05 '13 12:10

Alireza


1 Answers

This is just a limitation of C# and CLR. Only primitive numeric values, string literals and null can be used as a value of a constant field. Expression trees are represented as a normal graph of objects and can't appear as a constant value.

like image 84
JaredPar Avatar answered Nov 15 '22 02:11

JaredPar