I saw an interesting tweet from @remitaylor yesterday.
"Cannot assign lambda expression to anonymous type property." :sadface: So I can't include a lambda as a value in any new { ... } in C#
Unfortunately, this is true. I tried it myself.
var x = new { F = s => s + 1 };
Console.WriteLine(x.F(1));
The C# compiler doesn’t know if the lambda is meant to be a delegate or an expression tree. The solution is to instantiate the one you want to create. In this case, let’s assume it’s a Func<int, int>.
var x = new { F = new Func<int, int>(s => s + 1) };
Console.WriteLine(x.F(1));
It would be nice if the compiler was a little more intelligent about what you’re trying to do. We typically are trying to create delegates. If we’re using plain numbers, we typically want integers. I think the C# compiler could benefit from better inference.