Reputation: 11791
All, I am trying to figure out how does lambda expression works in the complied time also in the run time. Say you have the source code like below.
Currently, I tried to quick watch the variable. But unfortunately. Can not make it to view the source code of the Fun
.Is there any other way to view what does actually code the Func<int> ageCalculator
run?. Thanks.
Updated
No lucky things in the reflector kind tools. Please see it in the dotPeek
. Thanks.
Updated 1
There are more items (Compiled generated class items) displayed in the tree when the option is enabled. But double-clicked these items. Just display the MyTempClass
source code no new thing. What does it suppose to display ? Thanks.
Upvotes: 0
Views: 1141
Reputation: 18474
The key issue is that by returning a Func you return a compiled lambda, you want to return an Expression<Func<int>>
instead. You can then call ToString()
to see its representation and Compile().Invoke()
to run it
Expression<Func<int>> AgeCalculator() {
int myAge = 30;
return () => myAge;
}
public void Closure() {
var ageCalculator = AgeCalculator();
Console.WriteLine(ageCalculator.ToString());
Console.WriteLine(ageCalculator.Compile().Invoke());
}
Upvotes: 1
Reputation: 4445
I'm not sure if this it's what you want, but LinqPad
has some views Tree
, IL
that maybe it's what you're looking for....
Upvotes: 0
Reputation: 59303
You can't see the C# source code, because there is none. There's a class generated automatically by the compiler, so the only thing you could see is intermediate code (IL). That IL code might be displayed as C# by other tools like Reflector (I don't have such a tool integrated in Visual Studio, so I can't try).
You can see it in dotPeek when you enable "Show compiler generated code":
Next, right click and choose "Decompiled sources" to show the generated code:
Upvotes: 1
Reputation: 15571
I can see some stuff not entirely being used as it is intended to. Please consider the code below:
class Program
{
static void Main(string[] args)
{
// You do not call the method to assign it to the variable,
// you point to the method (without parentheses)
Func<int> answer = GetTheAnswerToEverything;
// Here you actually call the method
Console.WriteLine(answer());
Console.ReadLine();
}
// This is the method that you call when you write **add()**
private static int GetTheAnswerToEverything() => 42;
}
In this example, you actually call the GetTheAnswerToEverything method when you invoke answer().
For more information, see Func Delegate
Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.
Upvotes: 0