I would like to get a delegate to a property´s set function. This is how I do today:
var property = typeof(IApplicationState).GetProperty(propertyName);
var action = (Action<IApplicationState, T>)Delegate.CreateDelegate(typeof(Action<IApplicationState, T>), null, property.GetSetMethod());
This works, but then I have know the name of the property.
Can I do this without using the name? Something like this:
var action = (Action<IApplicationState, T>)Delegate.CreateDelegate(typeof(Action<IApplicationState, T>), null, IApplicationState.PROPERTY.GetSetMethod());
One simple option which does introduce an extra hop (but would probably have negligible performance impact) would be to just use a lambda expression:
Action<IApplicationState, T> action = (state, value) => state.Foo = value;
There's currently no way of referring to a property at compile-time in the same way as we can refer to a type with typeof
- although it's on the C# team's feature request list.
EDIT: If this is in a generic method (with a type parameter of T
), it's not at all clear to me that you'll be able to use this directly, as state.Foo
would presumably have to be of type T
(or object
perhaps). We can't really help with that aspect without more context of what you're trying to achieve.
See more on this question at Stackoverflow