Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# decimal.compare vs. > or <

Tags:

c#

comparison

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

like image 374
CountCet Avatar asked Dec 02 '08 15:12

CountCet


3 Answers

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.

like image 114
Jon Skeet Avatar answered Oct 21 '22 18:10

Jon Skeet


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.

like image 26
Joe Avatar answered Oct 21 '22 17:10

Joe


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.

like image 25
Jeffrey L Whitledge Avatar answered Oct 21 '22 18:10

Jeffrey L Whitledge