views:

54

answers:

3

Is there a way that I can track and intercept calls to values in properties that are auto implemented?

I'd like to have code that looks a bit like this:

[Tracked]
public int SomeProperty { get; set; }

Ideally the attribute would be able to intercept changes to the property values. Is this possible?

What I don't want it to have a second piece of code spin over an object later and request the values, but rather the attribute should tack the value as it is being set.

+4  A: 

No. The way you do this is by not using auto properties. The only possible solution there is, is to use something like Castle AOP to create automatic wrappers around your class and have that track the changes, but this is a lot of difficult work to implement.

Pieter
+3  A: 

You should be able to do this with an AOP framework, such as PostSharp (which I note is now commercial). There are a few more linked here, but some of the links are dead.

Noon Silk
+2  A: 

If you want a solution that works at runtime, then you'll want an aspect-oriented programming (AOP) framework; I've used CciSharp with some success. It's not as mature as PostSharp, but works on the same basic principle: it will modify your already-compiled code, producing another assembly.

If you are just wanting this for testing (or profiling), then there is another option: Microsoft Moles (which is also free). It works very differently; it uses a "detour" type of injection to change the program while it's running, intercepting the property getter and setter methods.

Stephen Cleary