Create a delegate from a property getter or setter method

Posted by thecoop on Stack Overflow See other posts from Stack Overflow or by thecoop
Published on 2010-04-12T11:04:27Z Indexed on 2010/04/12 11:13 UTC
Read the original article Hit count: 421

Filed under:
|
|

To create a delegate from a method you can use the compile-safe syntax:

private int Method() { ... }

// and create the delegate to Method...
Func<int> d = Method;

A property is a wrapper around a getter and setter method, and I want to create a delegate to a property getter method. Something like

public int Prop { get; set; }

Func<int> d = Prop;
// or...
Func<int> d = Prop_get;

Which doesn't work, unfortunately. I have to create a separate lambda method, which seems unnecessary when the setter method matches the delegate signature anyway:

Func<int> d = () => Prop;

In order to use the delegate method directly, I have to use nasty reflection, which isn't compile-safe:

// something like this, not tested...
MethodInfo m = GetType().GetProperty("Prop").GetGetMethod();
Func<int> d = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), m);

Is there any way of creating a delegate on a property getting method directly in a compile-safe way, similar to creating a delegate on a normal method at the top, without needing to use an intermediate lambda method?

© Stack Overflow or respective owner

Related posts about c#

Related posts about delegate