.NET Framework Expression for retrieving a static field


Having example type like this:

public TestClass
    public static string StaticPublicField = "StaticPublicFieldValue";

We can retrieve value of StaticPublicField:

var fieldExpr = Expression.Field(null, typeof(TestClass), "StaticPublicField");
var labmda = Expression.Lambda<Func<string>>(fieldExpr);

It can be then i.e. compiled into a delegate for retrieving field value.

Func<string> retriever = lambda.Compile();
var fieldValue = retriever();

//fieldValue result is StaticPublicFieldValue