I recently was given the opportunity to revisit Func<T> and Expression<T>. These things can become extremely complex and almost impossible to understand or read. So if you are as confused as I was when starting this here is how the Expression<T> vs. Func<T> relates.
Just bear in mind that you rarely want to deal with Expressions. Given the circumstances I was unfortunately forced to as I was hooking into an existing query expression.
To start off - the following statement is very important and very true:
So - an Expression is actually not a method that can execute in its own right.
- An Expression is merely meta-data about a function that can be compiled and then executed.
- A Function is executable code that you can call and use directly.
Looking at the example below - you will find a Func<int> (line 12) and an Expression<Func<int>> (line 13). Both return an integer of the value 10. The function can be executed directly by calling .invoke() (line 21) whereas the Expression first need to see a compilation (line 22) and then an invocation.
In other words - the expression is actually as the name suggests just an “expression” (a statement) about a future method (function) that it can be compiled into. Then, and only then can it (the compiled function) be used.
Need I say again - you do not need to deal with Expressions…?