Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top