Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to pass the setter of a property to a delegate?

I know this question has already been asked, but this time I have two additional constraints:

  1. Reflection cannot be used.

  2. I don't want to pass a wrapper around a property's setter. I want to pass the setter itself:

    // NO! NO! NO!
    myObject.MyMethod(value => anotherObject.AnotherProperty = value);
    
like image 775
pyon Avatar asked Jun 28 '11 18:06

pyon


1 Answers

Define this helper function(You'll need to add the error checking):

Action<TObject,TValue> GetSetter<TObject,TValue>(Expression<Func<TObject,TValue>> property)
{
    var memberExp=(MemberExpression)property.Body;
    var propInfo=(PropertyInfo)memberExp.Member;
    MethodInfo setter=propInfo.GetSetMethod();
    Delegate del=Delegate.CreateDelegate(typeof(Action<TObject,TValue>),setter);
    return (Action<TObject,TValue>)del;
}

And use it like this:

Action<MyClass,int> setter=GetSetter((MyClass o)=>o.IntProperty);

This is not exactly what you want(It uses reflection), but probably as close as you'll get. The returned delegate is the setter itself, no wrapper.

like image 117
CodesInChaos Avatar answered Oct 25 '22 03:10

CodesInChaos