Expression.Field Method (Expression, String)

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Creates a MemberExpression that represents accessing a field given the name of the field.

Namespace:   System.Linq.Expressions
Assembly:  System.Core (in System.Core.dll)

public static MemberExpression Field(
	Expression expression,
	string fieldName
)

Parameters

expression
Type: System.Linq.Expressions.Expression

An Expression whose Type contains a field named fieldName. This can be null for static fields.

fieldName
Type: System.String

The name of a field to be accessed.

Return Value

Type: System.Linq.Expressions.MemberExpression

A MemberExpression that has the NodeType property equal to MemberAccess, the Expression property set to expression, and the Member property set to the FieldInfo that represents the field denoted by fieldName.

Exception Condition
ArgumentNullException

expression or fieldName is null.

ArgumentException

No field named fieldName is defined in expression.Type or its base types.

The Type property of the resulting MemberExpression is equal to the FieldType property of the FieldInfo that represents the field denoted by fieldName.

This method searches expression.Type and its base types for a field that has the name fieldName. Public fields are given preference over non-public fields. If a matching field is found, this method passes expression and the FieldInfo that represents that field to Field.

The following code example shows how to create an expression that represents accessing a field.

// Add the following directive to your file:
// using System.Linq.Expressions;  

class TestFieldClass
{
    int sample = 40;
}

static void TestField()
{       
    TestFieldClass obj = new TestFieldClass();

    // This expression represents accessing a field.
    // For static fields, the first parameter must be null.
    Expression fieldExpr = Expression.Field(
        Expression.Constant(obj),
        "sample"
    );

    // The following statement first creates an expression tree,
    // then compiles it, and then runs it.
    Console.WriteLine(Expression.Lambda<Func<int>>(fieldExpr).Compile()());
}

// This code example produces the following output:
//
// 40

Universal Windows Platform
Available since 8
.NET Framework
Available since 3.5
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
Show: