In C#, are lambda expressions objects? If so, what sort of object are they?
+4
A:
Lambda operations in Linq build what are called expression trees. You can read a bit about it here.
ravuya
2009-06-25 14:17:24
Well they might. Or they might build delegates. It depends on the provider.
Jon Skeet
2009-06-25 14:21:43
+11
A:
Yes, lambda expressions are converted to either a delegate
or an expression tree - both of which are objects.
Andrew Hare
2009-06-25 14:17:40
A:
It's an anonymous function that has to conform to some kind of delegate. msdn So, in fact, they're instances of some delegate type.
Frederik Gheysels
2009-06-25 14:19:20
+15
A:
Lambda expressions themselves only exist in source code. They don't have a type themselves, which is why the compiler always insists they're convert to a specific type.
That's why this code doesn't compile:
// No idea what type to convert to!
object x = y => y.Length;
But this does:
Func<string, int> x = y => y.Length;
Lambda expressions are always converted to either a delegate type or an expression tree type. Similarly, anonymous methods are always converted to a delegate type.
Jon Skeet
2009-06-25 14:23:10
+1 Nice answer. I like that you explain how lambda expressions are really just syntax sugar for either a delegate or an expression tree.
Andrew Hare
2009-06-25 15:01:24