tags:

views:

1326

answers:

3

What would be the benefit of using decimal.compare vs. just using a > or < to compare to variables?

+1  A: 

In the CLI, decimal is not a native type like Int32, String, and others are. I am guessing that C# uses Compare behind the scenes to implement the comparison operators.

Also, you can pass Compare as a parameter to a sort routine without creating a delegate, reducing the method-nesting levels inside the sort.

That’s a couple of things off the top of my head.

Jeffrey L Whitledge
No, C# will use the operator overloads - that's what they're there for. Also if you pass Compare as a parameter it *is* creating a delegate - but you're right that you don't need to write the delegate implementation yourself.
Jon Skeet
So it uses bool [mscorlib]System.Decimal::op_LessThan(valuetype [mscorlib]System.Decimal, valuetype [mscorlib]System.Decimal), etc.? OK, I see what you mean.
Jeffrey L Whitledge
+4  A: 

For one thing it makes it really easier to build a Comparison<decimal> delegate instance:

Comparison<decimal> foo = decimal.Compare;

This is handy to pass into things which take arbitrary comparison delegates.

It may also be useful if you're using a language which doesn't support overloaded operators. That's the reason it's recommended that you don't expose functionality which is only supported by operators.

Jon Skeet
+3  A: 

Decimal.Compare returns a signed number indicating the relative values of two decimal values. A typical use of this is for sorting.

Operators such as >, >=, < return a boolean.

So they're used in difference scenarios.

Joe