tags:

views:

37

answers:

4

Is there a way to do this:

class Example {
    [ChangeNotification]
    private int field;
}

Such that changing the value of "field" would automatically get logged, generate an event, etc?

+1  A: 

No, attributes are type specific, not instance specific.

But you can implement INotifyPropertyChanged on all you objects and have some class listen to all the events and do the logging.

klausbyskov
Why cant you have a base class that does some magic based on those attributes? (I realize my point is pretty useless with fields as per the OP's example code, just noting how you can use them 'instance specific')
leppie
@leppie: Because the ability to know that the value *has* changed lies with the implementing function (in this case, there isn't even a setter function). Unless you either mandate (through policy, not code) the use of a central backing store (`Dictionary` or something similar), you'd have to no greater ability to know that the value has changed from the perspective of a base class than you would from external code. While something like PostSharp could automatically implement the interface for you, what you're suggesting, strictly speaking, is impossible.
Adam Robinson
@leppie, you cannot do that because the base class will never be notified about the changes, solely based on an attribute. The attribute is on the type and not on the instance. So the base class could definitely find all the fields with a given attribute but it would never know when to do anything, because it is never notified of any changes. INotifyPropertyChanged is really the best bet.
klausbyskov
unless of course the base class was to create a clone of all the original values with that given attribute, and (busy)check for changes. So it's probably doable, but definitely not recommendable.
klausbyskov
leppie
@klausbyskov: LOL that would be very sneaky, but quite feasable with correctly decorated classes.
leppie
@klausbyskov: Only a mind consumed by pure evil would even be able to imagine such a class.
Adam Robinson
@Adam, well, now you know a little more about me then ;-)
klausbyskov
A: 

At first view, I would better recommend that you implement the INotifyPropertyChanged interface, as an Attribute is type specific.

Will Marcouiller
A: 

You can do something similar (at least to a property, but not to a field) via Aspect oriented programming. However, this requires the use of a program like PostSharp, which actually rewrites the code inline based on the attribute.

Typically, this is used to implement INotifyPropertyChanged on a property. However, there are rewrite rules for logging and other features available.

This won't work for a field, however. It does work for a property, since the rewriter can add code to the property set method, but a field is handled directly by the CLR.

Reed Copsey
A: 

yes it's possible with postsharp using OnFieldAccessAspect http://www.sharpcrafters.com/forum/Topic2244-4-1.aspx

sirmak