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.
Related
See https://stackoverflow.com/questions/41810306/appointment-scheduling....
There are two problems with your code.
The first is how you are declaring your method:
Func<T, bool> ComposeFilter
When you do that, you are returning a compiled delegate, and the Where extension method overload that gets chosen is from Enumerable instead of Queryable.
You have to declare it as:
Expression<Func<T, bool>> ComposeFilter
The second problem is that the code you wrote cannot be converted to an expression tree. Since you are not using primitives but constructing the expression dynamically, you need to learn about the stuff in System.Linq.Expressions.
Say I have a method with an input parameter named collectionSelector of type Func<TEntity, ICollection<TCollection>>.
I'd like to use this input parameter to load EF entities by using this method on an instance of DbContext:
context.Entry(entity).Collection(collectionExpression).Load()
The Collection method accepts a parameter of type Expression<Func<TEntity, ICollection<TElement>>>
I've searched around, but can't figure out how to initialize an Expression instance from an Func instance. Anyone an idea? Thanks in advance!
How about if you define your method to take an expression:
void Process(Expression<Func<TEntity,ICollection<TCollection>>> collectionSelector)
{
context.Entry(entity).Collection(collectionExpression).Load()
}
Now you can call it passing in a lambda:
Process(x=>x.GenerateCollection());
And the C# compiler will take care of converting the lambda to an expression for you.
I've searched around, but can't figure out how to initialize an Expression instance from an Func instance.
You can't. A Func is a delegate that points to a compiled method, there's no way to get an expression tree from that (well, maybe it's possible, but certainly not easily since you would need to decompile the method).
Depending on the context, a lambda expression can be compiled either to an anonymous method or to an expression tree. There is no conversion between the method and the expression...
I'm wondering what exactly is the difference between wrapping a delegate inside Expression<> and not ?
I'm seeing Expression<Foo> being used a lot with LinQ, but so far I've not found any article that explains the difference between this, and just using a delegate.
E.g.
Func<int, bool> Is42 = (value) => value == 42;
vs.
Expression<Func<int, bool>> Is42 = (value) => value == 42;
tl;dr, To have an expression is like having the source code of an application, and a delegate is an executable to run the application. An expression can be thought of as the "source" (i.e., syntax tree) of the code that would run. A delegate is a specific compilation that you would run and does the thing.
By storing a lambda as a delegate, you are storing a specific instance of a delegate that does some action. It can't be modified, you just call it. Once you have your delegate, you have limited options in inspecting what it does and whatnot.
By storing a lambda as an expression, you are storing an expression tree that represents the delegate. It can be manipulated to do other things like changing its parameters, changing the body and make it do something radically different. It could even be compiled back to a delegate so you may call it if you wish. You can easily inspect the expression to see what its parameters are, what it does and how it does it. This is something that a query provider can use to understand and translate an expression to another language (such as write an SQL query for a corresponding expression tree).
It is also a whole lot easier to create a delegate dynamically using expressions than it is emitting the code. You can think of your code at a higher level as expressions that is very similar to how a compiler views code instead of going low-level and view your code as IL instructions.
So with an expression, you are capable to do much more than a simple anonymous delegate. Though it's not really free, performance will take a hit if you run compiled expressions compared to a regular method or an anonymous delegate. But that might not be an issue as the other benefits to using expressions may be important to you.
Func<> is just a delegate type. An Expression is a runtime representation of the complete tree of operations which, optionally, may be compiled at runtime into a delegate. It's this tree that is parsed by Expression parsers like Linq-to-SQL to generate SQL statements or do other clever things. When you assign a lambda to an Expression type, the compiler generates this expression tree as well as the usual IL code. More on expression trees.
To illustrate other answers, if you compile those 2 expressions and have look at the compiler generated code, this i what you will see:
Func<int, bool> Is42 = (value) => value == 42;
Func<int, bool> Is42 = new Func<int, bool>((#value) => value == 42);
Expression<Func<int, bool>> Is42 = (value) => value == 42;
ParameterExpression[] parameterExpressionArray;
ParameterExpression parameterExpression = Expression.Parameter(typeof(int), "value");
Expression<Func<int, bool>> Is42 = Expression.Lambda<Func<int, bool>>(Expression.Equal(parameterExpression, Expression.Constant(42, typeof(int))), new ParameterExpression[] { parameterExpression });
Expression Trees allow you to inspect the code inside the expression, in your code.
For example, if you passed this expression: o => o.Name, your code could find out that the Name property was being accessed inside the expression.
Provides the base class from which the classes that represent
expression tree nodes are derived.
System.Linq.Expressions.BinaryExpression
System.Linq.Expressions.BlockExpression
System.Linq.Expressions.ConditionalExpression
System.Linq.Expressions.ConstantExpression
System.Linq.Expressions.DebugInfoExpression
System.Linq.Expressions.DefaultExpression
System.Linq.Expressions.DynamicExpression
System.Linq.Expressions.GotoExpression
System.Linq.Expressions.IndexExpression
System.Linq.Expressions.InvocationExpression
System.Linq.Expressions.LabelExpression
System.Linq.Expressions.LambdaExpression
System.Linq.Expressions.ListInitExpression
System.Linq.Expressions.LoopExpression
System.Linq.Expressions.MemberExpression
System.Linq.Expressions.MemberInitExpression
System.Linq.Expressions.MethodCallExpression
System.Linq.Expressions.NewArrayExpression
System.Linq.Expressions.NewExpression
System.Linq.Expressions.ParameterExpression
System.Linq.Expressions.RuntimeVariablesExpression
System.Linq.Expressions.SwitchExpression
System.Linq.Expressions.TryExpression
System.Linq.Expressions.TypeBinaryExpression
System.Linq.Expressions.UnaryExpression
http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx
Expression tree represents linq expression that can be analyzed and for example turned into SQL query.
To whatever the other wrote (that is completely correct) I'll add that through the Expression class you can create new methods at runtime. There are some limits. Not all the things you can do in C# can be done in an Expression tree (at least in .NET 3.5 . With .NET 4.0 they have added a great number of possible Expression "types"). The use of this could be (for example) to create a dynamic query and pass it to LINQ-to-SQL or do some filtering based on the input of the user... (you could always do this with CodeDom if all you wanted was a dynamic method incompatible with LINQ-to-SQL, but emitting directly IL code is quite difficult :-) )
Both snippets below product the same output.
I understand how Func encapsulates a method with a single parameter, and returns a bool value. And you can either assign it a
method, anonymous method or a lambda expression.
Func<int, bool> deleg = i => i < 5;
Console.WriteLine("deleg(4) = {0}", deleg(4));
Below is using expression trees which I don't fully understand yet. Why would I want to do it this way? Is it more flexible, what advantage does it give me?
System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5;
Func<int, bool> deleg2 = expr.Compile();
Console.WriteLine("deleg2(4) = {0}", deleg2(4));
Basically, the Expression tree is the body of a lambda expression, that allows you to
introspect the expression (see what's in it so to say)
manipulate the expression (simplify, extend (e.g. add new functionality or modify to work on different items).
Once you Compile() the expression, it is just another delegate, which you can only call, not inspect or modify.
Whenever you want to
create expressions dynamically (I mean: construct, not allocate)
operate on expressions dynamically
the Function<> types are not sufficient.
The point of expression trees is that you can do more with them than just compile them to a function. You can inspect them, modify them and compile them to something other than .net functions.
For example Linq2SQL compiles expression trees to SQL code. You couldn't do that with a plain .net function.
In your first example you just have "hardcoded" the body of the function and assigned it to a delegate.
In your second example the assignment constructs an expression-tree which is an object model reprensenting your code in a data structure in memory.
The advantage is that you can modify and inspect that datastructure.
LINQ2SQL for example uses that technique to translate your expressions to another language called SQL.
Expression trees are regular in-memory data structures that can be traversed programmatically and the result of such traversal can be something, like a query you'd like to send to the database. Read more on the ExpressionVisitor class to see how it is done.
On the other hand, the compiled function is nothing more than a sequence of CIL code. You still can inspect it programmatically but you are not inspecting the definition but rather - the compiler output of it.
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.