Expression.PropertyOrField(Expression, String) Method

Definition

Creates a MemberExpression that represents accessing a property or field.

C#
public static System.Linq.Expressions.MemberExpression PropertyOrField(System.Linq.Expressions.Expression expression, string propertyOrFieldName);

Parameters

expression
Expression

An Expression whose Type contains a property or field named propertyOrFieldName.

propertyOrFieldName
String

The name of a property or field to be accessed.

Returns

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

Exceptions

expression or propertyOrFieldName is null.

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

Examples

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

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

class TestClass
{
    public int sample { get; set; }
}

static void TestPropertyOrField()
{
    TestClass obj = new TestClass();
    obj.sample = 40;

    // This expression represents accessing a property or field.
    // For static properties or fields, the first parameter must be null.
    Expression memberExpr = Expression.PropertyOrField(
        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>>(memberExpr).Compile()());
}

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

Remarks

The Type property of the resulting MemberExpression is equal to the PropertyType or FieldType properties of the PropertyInfo or FieldInfo, respectively, that represents the property or field denoted by propertyOrFieldName.

This method searches expression.Type and its base types for an instance property or field that has the name propertyOrFieldName. Static properties or fields are not supported. Public properties and fields are given preference over non-public properties and fields. Also, properties are given preference over fields. If a matching property or field is found, this method passes expression and the PropertyInfo or FieldInfo that represents that property or field to Property or Field, respectively.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0