Bookmark and Share

Anonymous Types and Lambdas

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.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.