Expression.MemberInit Method (NewExpression, MemberBinding[])
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Creates a MemberInitExpression.
Assembly: System.Core (in System.Core.dll)
public static MemberInitExpression MemberInit( NewExpression newExpression, params MemberBinding[] bindings )
Parameters
- newExpression
- Type: System.Linq.Expressions.NewExpression
A NewExpression to set the NewExpression property equal to.
- bindings
- Type:
System.Linq.Expressions.MemberBinding
[]
An array of MemberBinding objects to use to populate the Bindings collection.
Return Value
Type: System.Linq.Expressions.MemberInitExpressionA 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 how to use the MemberInit(NewExpression, MemberBinding[]) method to create a MemberInitExpression that represents the initialization of two members of a new object.
class Animal { public string Species { get; set; } public int Age { get; set; } } public static void CreateMemberInitExpression(System.Windows.Controls.TextBlock outputBlock) { System.Linq.Expressions.NewExpression newAnimal = System.Linq.Expressions.Expression.New(typeof(Animal)); System.Reflection.MemberInfo speciesMember = typeof(Animal).GetMember("Species")[0]; System.Reflection.MemberInfo ageMember = typeof(Animal).GetMember("Age")[0]; // Create a MemberBinding object for each member // that you want to initialize. System.Linq.Expressions.MemberBinding speciesMemberBinding = System.Linq.Expressions.Expression.Bind( speciesMember, System.Linq.Expressions.Expression.Constant("horse")); System.Linq.Expressions.MemberBinding ageMemberBinding = System.Linq.Expressions.Expression.Bind( ageMember, System.Linq.Expressions.Expression.Constant(12)); // Create a MemberInitExpression that represents initializing // two members of the 'Animal' class. System.Linq.Expressions.MemberInitExpression memberInitExpression = System.Linq.Expressions.Expression.MemberInit( newAnimal, speciesMemberBinding, ageMemberBinding); outputBlock.Text += memberInitExpression.ToString() + "\n"; // This code produces the following output: // // new Animal() {Species = "horse", Age = 12} }