tags:

views:

75

answers:

2

I would like to get a getter of a property so I could pass to a method that requires Func. For now I extracted getter to a Get method and I use this method when I need the getter function.

Few words about background: I have class A with properties and I have another class T which keeps track of some properties from A (and from class B, C, etc.). Keeping track means here that when object of T is asked about current values of tracked properties it should give such.

One approach could be change notification mechanism, but class A does not know what is tracked or not -- so it is quite wrong approach. You have to rewrite all classes that might be tracked. Moreover notifications have to be send all the time, even if tracker won't be asked about values at all.

It seems more handy to simply pass a method how to read the value (getter of property) and tracker will use it when required. No overhead, pretty straightforward.

+3  A: 
var getter = typeof(DateTime).GetProperty("Now").GetGetMethod();
var func = Delegate.CreateDelegate(getter, typeof(Func<DateTime>)) 
               as Func<DateTime>;
leppie
+5  A: 

Compiled code, or reflection? As a delegate, you can just use:

Func<Foo, int> func = x => x.SomeValue;

or to track the specific object:

Func<int> funct = () => someObj.SomeValue;

With reflection you would need GetGetMethod() and Delegate.CreateDelegate()

Marc Gravell
Why I didn't think of that? Beauty, thank you very much!
macias
This is why we are all going nuts about lambdas in c# ;)
Daren Thomas