ASP.NET Delegates and Expressions -Information Request - c#

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?.

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.

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.

Related

How to debug Lazy<T>?

I have a Lazy<T> initialized with a lambda. How to see the body of the initializing lambda while debugging? I expect to have something like the DebugView of the Expression class but I've found nothing like that.
Because Lazy<T> takes a delegate, there is no Expression class involved. Your lambda is compiled like any other code in your project and there is no preview of that code during debug.
Lambda expression can be compiled either into IL or transformed into Expression Tree. Which one happens depends on the context. If your parameter is declared as delegate regular IL code will be generated. If it's Expression<TFunc> you'll get expression tree which can be previewed.
It's nicely explained on MSDN, based on Where method, which has two versions: Enumerable.Where which takes Func<T, bool> and Queryable.Where which takes Expression<Func<T, bool>>.
When you use method-based syntax to call the Where method in the
Enumerable class (as you do in LINQ to Objects and LINQ to XML) the
parameter is a delegate type System.Func<T, TResult>. A lambda
expression is the most convenient way to create that delegate. When
you call the same method in, for example, the System.Linq.Queryable
class (as you do in LINQ to SQL) then the parameter type is an
System.Linq.Expressions.Expression<Func> where Func is any of the Func
delegates with up to sixteen input parameters. Again, a lambda
expression is just a very concise way to construct that expression
tree. The lambdas allow the Where calls to look similar although in
fact the type of object created from the lambda is different.

What exactly is the type of lambda expression with a body?

Windows forms extension method Invoke() doesn't accept a lambda expression, without us having to first typecast it to a delegate type like Action. This makes me wonder, if lambda expression (with a body) is not explicitly a delegate nor an expression, what is its type?
This makes me wonder, if lambda expression (with a body) is not explicitly a delegate nor an expression, what is its type?
It doesn't have a type in the normal sense of the word (i.e. a CLR type), just like null doesn't have a type. (Older versions of the C# specification had the concept of a "null type", but that was removed.)
Instead, it's an expression which is convertible to any compatible concrete delegate or expression tree type.
See section 7.1 of the C# 5 specification ("Expression Classification") for details - the relevant bullet points (out of the list of kinds of expression) are:
A null literal. An expression with this classification can be implicitly converted to a reference type or nullable type.
An anonymous function. An expression with this classification can be implicitly converted to a compatible delegate type or expression tree type.
Delegate is an abstract base class for all the delegates(MulticastDelegate comes in between). Lambda can't be converted to Delegate type as it can't be instantiated, and it doesn't have any signature.
So, You need to be more specific in saying what delegate type you're interested.
what is its type?
It has no type, it can be converted to any delegate type or Expression<TDelegate> type if the signature is compatible.

What Is => Called and How Is It Used in C# [duplicate]

This question already has answers here:
C# Lambda ( => ) [duplicate]
(4 answers)
Closed 9 years ago.
I have seen => used in sample code, but I don't know what this operand is called. Because the term is just symbols, Google search is not very helpful.
Here is an example of its use:
var rolesAllowed = rolePermission.Where(permission => permission.Permissions.Any(p => Demand.HasFlag(p.Type))).ToList();
This question is different from the ones so brazenly marked as "duplicate". I was looking for the name of the expression so I could research how to use it. The so-called duplicate item was for someone who already knew that => was called a lambda expression.
I want to thank the people who took the time to read and understand the question, and post a quality response.
It is called Lambda operator
To create a lambda expression, you specify input parameters (if any)
on the left side of the lambda operator =>, and you put the expression
or statement block on the other side. For example, the lambda
expression x => x * x specifies a parameter that’s named x and returns
the value of x squared.
Lambda expressions use special syntax. They allow functions to be used as data such as variables or fields. The lambda expression syntax uses the => operator. This separates the parameters and statement body of the anonymous function.
The => operator can be read as "goes to" and it is always used when declaring a lambda expression.
That is used to for lambda expressions. Essentially what that the Where function takes in is another function that iterates through the collection. The left side of the => defines the parameters and the right side is the actual function that gets run.
It is called lambda operator and it's the part of the lambda expression syntax.
Lambda expressions are very concise way to create anonymous methods.
Anonymous method example:
button1.Click += delegate(System.Object o, System.EventArgs e)
{ MessageBox.Show("Click!"); };
The same code, but this time using lambda expression:
button1.Click += (o,e) => MessageBox.Show("Click!");
As shown, this syntax is a
great shorthand notation for authoring anonymous methods, where a stack of arguments can be passed
into a group of statements for processing. Any method in the .NET platform that takes a delegate object
as an argument can be substituted with a related lambda expression, which will typically simplify your
code base quite a bit.
This is the lambda operator, it creates a lambda expression, which is like an anonymous method.
=> is a lambda operator, check the link to read more.
Also check this answer for more details.

C# A question about the lambda expression as a method parameter

At the page code.google.com/p/fakeiteasy/ I've noticed the line:
A.CallTo(() => shop.GetTopSellingCandy()).Returns(lollipop);
so the question is - how to pass a lambda expression as a method parameter ?
This function takes a parameter of type Func<T> (A normal delegate with a generic parameter), or, more likely, Expression<Func<T>> (an expression tree).
The function itself probably has a generic parameter which is inferred from the method passed.
By taking an expression tree, the function is able to inspect the code inside the expression and see what it does.
The code you've given is doing exactly that - passing a lambda expression as a paramter to a method call.
CallTo might have the signature 'CallTo(Action action)'. So lambda is passed as a delegate

Is it possible to cast a delegate instance into a Lambda expression?

Here the context for my question:
A common technique is to declare the parameter of a method as a Lambda expression rather than a delegate. This is so that the method can examine the expression to do interesting things like find out the names of method calls in the body of the delegate instance.
Problem is that you lose some of the intelli-sense features of Resharper. If the parameter of the method was declared as a delegate, Resharper would help out when writing the call to this method, prompting you with the x => x syntax to supply as the argument value to this method.
So... back to my question I would like to do the follow:
MethodThatTakesDelegate(s => s.Length);
}
private void MethodThatTakesDelegate(Func<string, object> func)
{
//convert func into expression
//Expression<Func<string, object>> expr = "code I need to write"
MethodThatTakesExpression(expr);
}
private void MethodThatTakesExpression(Expression<Func<string, object>> expr)
{
//code here to determine the name of the property called against string (ie the Length)
}
Everywhere that you're using the term "lambda expression" you actually mean "expression tree".
A lambda expression is the bit in source code which is
parameters => code
e.g.
x => x * 2
Expression trees are instances of the System.Linq.Expressions.Expression class (or rather, one of the derived classes) which represent code as data.
Lambda expressions are converted by the compiler into either expression trees (or rather, code which generates an expression tree at execution time) or delegate instances.
You can compile an instance of LambdaExpression (which is one of the subclasses of Expression) into a delegate, but you can't go the other way round.
In theory it might be possible to write such a "decompiler" based on the IL returned by MethodBase.GetMethodBody in some situations, but currently there are various delegates which can't be represented by expression trees. An expression tree represents an expression rather than a statement or statement block - so there's no looping, branching (except conditionals), assignment etc. I believe this may change in .NET 4.0, though I wouldn't expect a decompilation step from Microsoft unless there's a really good reason for one.
I don't believe it's possible to achieve what you'd like here. From the comments in your code it looks like you are attempting to capture the name of the property which did the assignment in MethodThatTakesExpression. This requires an expression tree lambda expression which captures the contexnt of the property access.
At the point you pass a delegate into MethodThatTakesDelegate this context is lost. Delegates only store a method address not any context about the method information. Once this conversion is made it's not possible to get it back.
An example of why this is not possible is that there might not even be a named method backing a delegate. It's possible to use ReflectionEmit to generate a method which has no name whatsoever and only exists in memory. It is possible though to assign this out to a Func object.
No, it is not possible.

Categories

Resources