MgSam
MgSam

Reputation: 12813

.NET Expressions - Property Initializers

I'm trying to find an example of how, with the .NET Expression library, to new up an object and assign properties using property initializers. Does anyone have an example of this?

Basically, I need Expression code equivalent to:

new Foo() { Bar = "bar", Baz = 5 }

I have Expression.New(constructorInfo) so far but I'm not sure how to add the property initializers.

Upvotes: 1

Views: 284

Answers (1)

canton7
canton7

Reputation: 42320

The most straightforward way is just to new up the object, then assign each of its properties. Since this involves multiple statements, you'll need to use a block. The last expression in the block is its return value.

var fooVariable = Expression.Variable(typeof(Foo));
var block = Expression.Block(new[] { fooVariable },
    Expression.Assign(fooVariable, Expression.New(typeof(Foo))),
    Expression.Assign(Expression.Property(fooVariable, "Bar"), Expression.Constant("bar")),
    Expression.Assign(Expression.Property(fooVariable, "Baz"), Expression.Constant(5)),
    fooVariable);

See it on dotnetfiddle.net.

You can also use Expression.MemberInit, which more accurately represents the object initializer:

var foo = Expression.MemberInit(
    Expression.New(typeof(Foo)),
    Expression.Bind(typeof(Foo).GetProperty("Bar"), Expression.Constant("bar")),
    Expression.Bind(typeof(Foo).GetProperty("Baz"), Expression.Constant(5)))

See it on dotnetfiddle.net.

Upvotes: 2

Related Questions