Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one should I use? decimal.Add() or "+"

Tags:

c#

.net

I have a question that I can not find the answer. Imagine that I have two decimal numbers. When I want to sum the numbers which one and why should I use?

option1:

var num1 = 10.456m;
var num2 = 12.033m;

var result = decimal.Add(num1, num2);

option2:

var num1 = 10.456m;
var num2 = 12.033m;

var result = num1 + num2;
like image 288
Muammer HALLAC Avatar asked Feb 26 '13 09:02

Muammer HALLAC


1 Answers

They are absolutely the same. The Decimal class has overloaded the + operator calling the same method. So you should use the one that you feel more readable. Personally I prefer the second approach.

+ operator (courtesy of reflector):

[SecuritySafeCritical, __DynamicallyInvokable]
public static decimal operator +(decimal d1, decimal d2)
{
    FCallAddSub(ref d1, ref d2, 0);
    return d1;
}

and the Add method:

[SecuritySafeCritical, __DynamicallyInvokable]
public static decimal Add(decimal d1, decimal d2)
{
    FCallAddSub(ref d1, ref d2, 0);
    return d1;
}

Strict equivalence in terms of IL and performance.

like image 98
Darin Dimitrov Avatar answered Oct 19 '22 09:10

Darin Dimitrov