views:

157

answers:

4

I'm trying to find the equivalent of PropertyInfo.AddValueChanged for FieldInfo. I basically just need to receive an event any time the field's value changes. I'm assuming there's nothing like this and I'll have to manipulate IL code or something like that. I'm willing to go that route, but any suggestions on how I should go about it? And is there an AddValueChanged equivalent for fields that I'm not aware of so I don't have to go that route?

Thanks.

A: 

Let me just confirm that there's nothing built-in like what you're after. Properties can easily implement that because the setter is a method, while fields by design don't have setter methods, their value is just modified and that can happen from any place in the code. To do what you're after, I think you could take a look at PostSharp.

emaster70
PostSharp seems like it should be capable of what I'm after because on of the features says, "Add behaviors to fields", but I can't seem to find an example showing that functionality.
Thrash505
+1  A: 

Why not just wrap the field in a property, and implement an event on change (ie: make your class INotifyPropertyChanged or your own equivelent)?

That's one the beautiful things about properties - they allow you to define behavior in this manner. Fields do not have any equivelent, and manipulating IL is not going to change this. As long as it's a field, it will not notify.

Reed Copsey
This is actually for a property grid type control that also works for fields and hashtables. Therefore I need to be notified when things are changed outside of my control. So wrapping things in a property is not an option because I'm not writing the class I'm reflecting.That's why I mentioned IL code... I was thinking that through some magic I could create a property at run-time to wrap up the field and send out an event in its set accessor...
Thrash505
Unfortunately, there's no way in .NET (in the CLR) to tell when a field changes. A field is just a value - you'd have to poll it regularly to look for changes if you want this behavior.
Reed Copsey
You seem to be correct, I've looked around for several days and I don't see any way to modify existing code at run-time; you can only create new types, etc. I'm going to go with pulling the field values every so often to check for changes. Thanks.
Thrash505
A: 

As indicated in the other answers, with the limited information you provided, I would suggest you make any value assignments via the field's accessor. If it needs to be outside of any class, you can create a separate class (or struc) (and put your field change in an accessor.) If you do not need multiple instances of the field, you can declare it static and only access it via its accesor.

mikeh
A: 

Are you exposing public fields that you are trying to monitor? It seems like you should wrap them in properties and expose them that way. Then you can use the monitoring code you've already got.

JP Alioto