0

I want to write a generic SetProperty method for a MVVM ViewModel which right now looks like this:

protected virtual bool SetProperty<T>(ref T storage, T value, string name)
{
    if (EqualityComparer<T>.Default.Equals(storage, value))
        return false;
    storage = value;
    OnPropertyChanged(name);
    return true;
}

The problem is that this would compare float-point values (float, double, decimal) with Equals instead of a Math.Abs(storage - value) < EPSILON as you should compare float-point values. The easy approach would be to check the two values whether they're float and then compare them. The same with double and decimal. Is there an easier way I compare two generic types whether they're float-point and compare them accordingly?

(I couldn't find any documentation if EqualityComparer<T>.Default already considers this)

Gregor A. Lamche
  • 402
  • 2
  • 5
  • 18
  • You could simply add methods like `protected bool SetProperty(ref double storage, double value, string name) { ... }` – Clemens Jun 23 '20 at 08:21
  • Do you really care about avoiding raising property changed? You've set a property to something. That somehow turns out to be the same value it already had. If you remove any equality check you always raise property changed. With no equality check then your ui doesn't really need to but gets that new value again. But so what? Is that overhead really significant? – Andy Jun 23 '20 at 09:05
  • And... Isn't it only float that is likely to cause this sort of problem? I usually round float to 4 dp for any equality comparison. – Andy Jun 23 '20 at 09:14
  • It's a performance thing, no need to update the UI if nothing changed. Not to mention that other things can attach to those property events which can cascade to more performance loss if it updates with the same value. It can be float, double, or decimal with the issue. – Gregor A. Lamche Jun 23 '20 at 09:18
  • 1
    If you are asking if there is some common "float-point" base type between `float`, `double` and `decimal`, the answer is no. If you want to treat these types different from the others you should either provide three specific overloads, or cast `value`. – mm8 Jun 23 '20 at 15:58

0 Answers0