C# > Linq > Expressions > Expression >
Compile
Compiles the lambda expression described by the expression tree into executable code and produces a delegate that represents the lambda expression.
Example
Get value from object using Lambda expression
using System;
using System.Linq.Expressions;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public class Project
{
public string Name { get; set; }
public int Id { get; set; }
}
public TProp GetValue(TObj obj, Expression<Func> prop)
{
return prop.Compile()(obj);
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var project = new Project();
project.Name = "Project 1";
project.Id = 1;
int id = GetValue(project, i => i.Id);
string name = GetValue(project, i => i.Name);
}
}
}