Reproduced. That is a strange error message from the compiler. I would expect instead:
error CS0134: '(field)' is of type '(type)'. A const field of a reference type
other than string can only be initialized with null.
The message we do get is misleading. Some C# expressions (I am not talking about .NET expression trees Expression<...>
) can clearly contain a lambda expression, but they don't say why this particular expression cannot.
The solution is to make a static readonly
field instead:
class MyClass
{
public static readonly Expression<Func<string, bool>> MyExpr
= s => s == "Hello!";
}
Only one instance of Expression<>
will ever be created, but it is no compile-time constant, there is actually some code that will run once (just) before MyClass
is used for the first time.
s
in another sense elsewhere? – Ullundpublic LambdaExpression...
instead ofpublic Expression<...
? – Neoarsphenamineconst
, you'd have to usereadonly
.const
requires that it be a compile-time constant; something you could imagine being copy/pasted wherever you useMyExpr
.readonly
will be resolved at runtime as though you just were referencing a field. – Neoarsphenamineconst
value of typeExpression<Func<string, bool>>
you can have, isnull
. But the error message was confusing. I have not tried to compile the above code myself (yet). – Ullund