2

I have a generic C# class comparer routine which reads values from objects and then compares their properties one by one using reflection.

            var value1 = property.GetValue(object1, null);
            var value2 = property.GetValue(object2, null);

            if (!value1.Equals(value2))
            { ......

Thing is I'm getting differences in some of my float/double values that are insignificant and I want to ignore. What's the best way of implementing a specific test for floats/doubles (and potentially ints) that compares values based on a provided number of significant digits?

MrTelly
  • 14,657
  • 1
  • 48
  • 81
  • 1
    I think that you should look at this thread: http://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp – user1068352 Dec 09 '11 at 13:20
  • I'm liking "....return Math.Abs(a - b) <= Math.Abs(a * epsilon);...", now is there a neat way of casting to float, double, int. – MrTelly Dec 09 '11 at 13:25

1 Answers1

1

Take a look at the EqualityComparer<T> class.

Instead of comparing objects in the way you describe, you should rely on the Equals method of the type in question, imho. That is, the author of the class should define when 2 instances of that class are equal, by overriding the Equals method (and perhaps even implementing the IEquality interface).

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
  • Yep I realise(d) that I could go that approach but there is no ISimilar interface which will take significant digits. Clearly I could implement that. And I could add the Similar method and then cook up some code for which fields of the object need to be similar and which are exact. I could then add all the code to my many different data objects .... 200-300 lines of boiler plate code later I'd still be wondering if there was a neat way of doing this - hence the question. – MrTelly Dec 09 '11 at 13:48