views:

85

answers:

2

Based on my understanding , i interpret the meaning of Func delegate as follows.Please correct them as and when it is needed.

Declaration : Func<int> dg ;

1. Could i interpret it as "a Delegate pointing to a method that returns an integer?".

Declaration : Func<int,int> delg1=r=>2*r;

*2. Could i interpret it as " 'r' is a lambda expression that itself is a parameter of an integer type being evaluated as '2 * r' and returns an int? .*

Comparison : Delegate and lambda expression

3. if both Delegates and lambdas are working as function poiinters ,Where do there differ?.

Comparison : Are the following two declarations equal?

decl 1 : Func<int,int> fn=(r)=>45*r;

decl 2 : Expression<Func<int,int>> ex = (r) => r * 10;

4. if both of the above mentioned constructs are serving for the same purpose ,Where do there differ?.

+2  A: 

Delegates and expressions are not the same thing. Delegates are strongly-typed references to methods while expressions are in-memory representations of code that can be treated as data. An expression can be compiled into IL (the Expression.Compile method) and this will give you a delegate to that newly compiled method.

Just remember that an expression can be turned into a delegate, but a delegate is just a delegate.

Andrew Hare
+8  A: 

1) Yes, but it would be more precise and accurate to say "a delegate referring to a method that takes no arguments and returns an integer".

2) No. "r" is not a lambda expression. "r" is used twice, first to declare a formal parameter of a lambda expression, and second as part of the body of that lambda expression. But "r" is not the lambda expression. The lambda expression is "r=>2*r"

3) Lambdas and delegates are different things. A lambda is the abstract notion of "a function that does some thing". A delegate type is the abstract notion of the type of things which are methods that take and return certain types. A particular delegate is a reference to such a method. A lambda is convertible to a compatible delegate type, and if you do so, at runtime, you get a delegate instance. But a lambda is convertible to other things as well, like an expression tree.

4) They do not serve the same purpose. The expression tree is an object which represents the computation mentioned in the lambda. The delegate is an object which actually performs the computation mentioned in the lambda.

Eric Lippert
+1 Brilliantly explained - well done :)
Andrew Hare