Expression.MemberInit Method (NewExpression, IEnumerable(Of MemberBinding))

 

Represents an expression that creates a new object and initializes a property of the object.

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

Public Shared Function MemberInit (
	newExpression As NewExpression,
	bindings As IEnumerable(Of MemberBinding)
) As MemberInitExpression

Parameters

newExpression
Type: System.Linq.Expressions.NewExpression

A NewExpression to set the NewExpression property equal to.

bindings
Type: System.Collections.Generic.IEnumerable(Of MemberBinding)

An IEnumerable(Of T) that contains MemberBinding objects to use to populate the Bindings collection.

Return Value

Type: System.Linq.Expressions.MemberInitExpression

A MemberInitExpression that has the NodeType property equal to MemberInit and the NewExpression and Bindings properties set to the specified values.

Exception Condition
ArgumentNullException

newExpression or bindings is null.

ArgumentException

The Member property of an element of bindings does not represent a member of the type that newExpression.Type represents.

The Type property of the resulting MemberInitExpression is equal to the Type property of newExpression.

The following example demonstrates an expression that creates a new object and initializes a property of the object.

' Add the following directive to your file:
' Imports System.Linq.Expressions  

Class TestMemberInitClass
    Public Property Sample As Integer
End Class

Sub MemberInit()
    ' This expression creates a new TestMemberInitClass object
    ' and assigns 10 to its Sample property.
    Dim testExpr As Expression = Expression.MemberInit(
        Expression.[New](GetType(TestMemberInitClass)),
        New List(Of MemberBinding)() From {
            Expression.Bind(GetType(TestMemberInitClass).GetMember("Sample")(0), Expression.Constant(10))
        }
    )

    ' The following statement first creates an expression tree,
    ' then compiles it, and then runs it.
    Dim test = Expression.Lambda(Of Func(Of TestMemberInitClass))(testExpr).Compile()()
    Console.WriteLine(test.Sample)
End Sub

' This code example produces the following output:
'
' 10

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: