greenoldman greenoldman - 4 months ago 23
C# Question

How to get a getter of a property?

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.


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()