Search code examples
c#.netdecimalnegate

.NET decimal.Negate vs multiplying by -1


Are there any differences between decimal.Negate(myDecimal) and myDecimal * -1 (except maybe readability)?


Solution

  • I suspect Negate exists because there's a unary minus operator (op_UnaryNegation), and it's good practice to have methods representing the equivalent functionality so that languages which don't support operator overloading can still achieve the same result.

    So instead of comparing it with myDecimal * -1 it may be helpful to think of it as being an alternative way of writing -myDecimal.

    (I believe it's also optimised - given the way floating point works, negating a value is much simpler than normal multiplication; there's just a bit to flip. No need to perform any actual arithmetic.)