C # The fastest way to find out something in an object has changed?

I want to know if the value of any of the private or public fields has changed. Is there any way other than exceeding GetHashCode () or calculating CRC?

The algorithm should also be fast.

-Thanks,

-Brajesh

+6
c #
source share
4 answers

This is usually done with the INotifyPropertyChanged interface ( link ). It is really practical to use it only with properties, not with fields. However, you can create private property for each of your personal fields. When you have everything as a property, edit the installer so that you check to see if the value has changed, and then call NotifyPropertyChanged() , if any.

Example:

 public event PropertyChangedEventHandler PropertyChanged; private int _foo; public int Foo { get { return _foo; } set { if (_foo != value) { _foo = value; NotifyPropertyChanged("Foo"); } } } private void NotifyPropertyChanged(string info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } 
+5
source share

You might want to encapsulate all of your data (which you want to track for changes) inside get / set accessors (aka properties).

Then, in installation access, check if the value has changed, set it to a new value and:

  • set _dirty to true (if you need to check it later)

or

  • raise an event of your choice

Some notes on CRC - even if you do not have a counter CRC / HASH algoritam for your object, you should have the original hash somewhere. But simple hashes are likely to be duplicated, so again you will have a speed problem.

+2
source share

If it should work for any type and should detect any changes, without false negatives or false positives, I see no better way than to copy all the field values โ€‹โ€‹for the link. Since you need this to be fast, I would recommend the following:

  • Write a procedure that uses reflection to make a shallow copy of all field values.

  • Write a procedure that compares fields by value (if you are looking for changes in nested structures, like arrays or collections, your problem is much more complicated.)

  • After doing the above work, you can use IL Emit and write code that does Reflection once, and emits code for a small batch file, copying and comparing. You now have several instances of DynamicMethod that you can use for each operation. It is pretty fast when they emit and tremble.

+1
source share

Insert a boolean value into each public setter, for example m_IsChanged, and then use the public getter only to check if one of the properties has been changed.

Example:

 private bool m_IsChanged = false; private double m_DoubleValue; //[...] all other private properties public double DoubleValue { get { return m_DoubleValue; } set { if(m_DoubleValue != value) m_IsChanged = true; m_DoubleValue = value; } } //[...] all other getters/setters public bool IsChanged { get { return m_IsChanged; } } 
+1
source share

All Articles