Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104702

Dynamic property setter with linq expressions?

I want to create a simple function that does the following:

Sub SetValue(Of TInstance As Class, TProperty)(
  ByVal instance As TInstance,
  ByVal [property] As Expression(Of Func(Of TInstance, TProperty)),
  ByVal value As TProperty)

  '...
End Sub

Usage:

Dim x As New Person
SetValue(x, Function(p) p.FirstName, "John Doe")

Upvotes: 1

Views: 676

Answers (1)

Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104702

It's actually pretty simple:

Sub SetValue(Of TInstance As Class, TProperty)(
   ByVal instance As TInstance,
   ByVal [property] As Expression(Of Func(Of TInstance, TProperty)),
   ByVal value As TProperty)


  'TODO: validate nulls
  If [property].Body.NodeType <> ExpressionType.MemberAccess Then _
    Throw New ArgumentException("Invalid lambda expression.", "property")


  Dim body = DirectCast([property].Body, MemberExpression)
  Dim member = DirectCast(body.Member, PropertyInfo)
  member.SetValue(instance, value, Nothing)
End Sub

HTH

Upvotes: 1

Related Questions