-1

I'm writing a general alerts system based on user-generated conditions. Test values & actual values are handled as objects since they could be numeric, boolean, or string depending on the selected property. It needs to be error tolerant and fail gracefully.

So I'm looking for a general purpose function in C# to make comparisons (greater/less/equal) for various data types.

Using the IComparable interface doesn't work as it is type-specific, for example this will crash if testValue is Int32 and comparsonValue is decimal:

object testValue = (int)10;
object comparisonValue = (decimal)11;

var comparison = ((IComparable)testValue).CompareTo(comparisonValue)

// Crashes with {System.SystemException}: {"Object must be of type Int32."}

Is there any other general purpose comparison function in C#? I hope I don't have to code everything up myself.

Brendan Hill
  • 3,406
  • 4
  • 32
  • 61
  • 4
    So what happens when someone asks if an int is less than a bool? – Eric Lippert Jan 16 '14 at 01:30
  • Graceful failure. It needs to be error-tolerant. – Brendan Hill Jan 16 '14 at 02:32
  • Wow, two downvotes? I'm a little lost. – Brendan Hill Jan 16 '14 at 02:34
  • By graceful do you mean handled? As in try-catch? – devilfish17 Jan 16 '14 at 02:43
  • write your own custom comparer for err-tolerant. all the stuffs in c# i knew are strong-typed. – Kelmen Jan 16 '14 at 03:11
  • @BrendanHill You need to define what "error tolerant" means. If the types don't match do you want it to say that they're equal, pick one to be larger, or just throw an exception? The existing implementation choose the latter, because it's the only sensible option. If you want it to do something else, create your own comparer and have it do...whatever else you want it to do. – Servy Jan 16 '14 at 03:19

1 Answers1

0

So in the face of 3 downvotes (ok, didn't think the question was THAT bad...) I will be writing my own custom comparer rather than searching for a non-type-specific version of IComparer.CompareTo.

Brendan Hill
  • 3,406
  • 4
  • 32
  • 61