In .NET both Action and Func classes are actually delegates that can be invoked to execute code, whereas the Expression class represents an expression tree that can potentially be compiled into executable code at run time. Expressions are particularly fun because they are malleable, and you can use them dynamically create delegates.
For example, you can create a generic statement that allows you to assign values to properties. This means that one piece of code can use a lambda to select a property for assignment, and another unrelated piece of code can use that expression to dynamically assign the value.
Thanks to AnxiousdeV for coming up with this solution on Stack Overflow.
Test
public class ExpressionTests
{
public int X { get; set; }
[Fact]
public void GetSetPropertyAction()
{
// Create an expression.
var expression = GetExpression<ExpressionTests, int?>(c => c.X);
// Use our extension method to create the action.
var assignAction = expression.GetSetPropertyAction();
// Set the property.
assignAction(this, 2);
// Assert that the value was set correctly.
Assert.Equal(2, X);
}
private static Expression<Func<T, U>> GetExpression<T, U>(
Expression<Func<T, U>> expression)
{
// We are only using this method to create an expression.
return expression;
}
}
