4 ms·
It's a compile time, not a runtime feature. It can't be implemented at runtime, if your method is passed an opaque compiled delegate, it's not possible for the
by mythz 7y ago
It's a compile time, not a runtime feature.
It can't be implemented at runtime, if your method is passed an opaque compiled delegate, it's not possible for the .NET Runtime to deconstruct its pre-compiled AST.
If your method accepts a `Expression<Func<T,bool>>` the C# compiler passes it the AST of the Expression instead of the compiled delegate.
For an example, paste the code below to https://sharplab.io https://sharplab.io
using System;
public class A {
A() => M<int>(x => x == 1);
public void M<T>(Func<T,bool> expr) {}
}
public class B {
B() => M<int>(x => x == 1);
public void M<T>(System.Linq.Expressions.Expression<Func<T,bool>> expr) {}
}
and look at what the compiler generates for class A vs class B's constructors.
- kjlkjljklkjl 7y agobut, Expression can be created from string, doesn't it?
- mythz 7y agoParsed by who, the C# compiler? I'm not aware of anything that generates C#'s Expression AST from a string, other than a C# Compiler. You can use Roslyn in code, but that's using the C# compiler in process.
- gpderetta 7y agoThe code->AST is done of course at compile time (there is no reason to delay), but I believe the expression tree itself is processed by linq at runtime. You can build expressions programmatically at runtime as well (and then ask the runtime to optmize them to bytecode). I remember doing it years ago, it was surprisingly simple (and very powerful).
- mythz 7y agoOf course the Expression's AST generated by the C# compiler is analyzed at runtime, how else could it be done?