Does a lambda expression create an object on the heap every time it’s executed?

It is equivalent but not identical. Simply said, if a lambda expression does not capture values, it will be a singleton that is re-used on every invocation. The behavior is not exactly specified. The JVM is given big freedom on how to implement it. Currently, Oracle’s JVM creates (at least) one instance per lambda expression … Read more

Is it possible to figure out the parameter type and return type of a lambda?

Funny, I’ve just written a function_traits implementation based on Specializing a template on a lambda in C++0x which can give the parameter types. The trick, as described in the answer in that question, is to use the decltype of the lambda’s operator(). template <typename T> struct function_traits : public function_traits<decltype(&T::operator())> {}; // For generic types, … Read more

Why would you use Expression rather than Func?

When you want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the expression and converts it to the equivalent SQL statement and submits it to server (rather than executing the lambda). Conceptually, Expression<Func<T>> is completely different from Func<T>. Func<T> denotes a delegate … Read more

Combining two expressions (Expression)

Well, you can use Expression.AndAlso / OrElse etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression in expr1 and expr2? If so, it is easier: var body = Expression.AndAlso(expr1.Body, expr2.Body); var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]); This also works well to negate a single operation: static Expression<Func<T, … Read more

Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)

If you have Guava in your project, you can use the Streams.zip method (was added in Guava 21): Returns a stream in which each element is the result of passing the corresponding element of each of streamA and streamB to function. The resulting stream will only be as long as the shorter of the two … Read more

Is there a reason for C#’s reuse of the variable in a foreach?

The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits. Your criticism is entirely justified. I discuss this problem in detail here: Closing over the loop variable considered harmful Is there something you can do with … Read more