5

Is it necessary to add M for zero values for assignment and comparisons of decimal variable?

decimal val;
...
if (val == 0M)
{
}

or

if (val == 0)
{
}

I guess the constant will be converted at compile time and the result will be identical.

i486
  • 6,491
  • 4
  • 24
  • 41
  • This could be useful: https://stackoverflow.com/questions/27269607/c-sharp-decimal-how-to-add-trailing-zeros?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Anand May 03 '18 at 09:36
  • Yes, `0` will be *implicitly* case to `decimal` at complie time: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit-numeric-conversions-table; however, we must put `M` after `0.0` since "There are no implicit conversions between floating-point types and the decimal type" – Dmitry Bychenko May 03 '18 at 09:36
  • 1
    The compiled IL is identical, so no it's not necessary in this situation. – DavidG May 03 '18 at 09:36
  • Duplicate question, The answer is here : https://stackoverflow.com/a/977562/4189817 – Mohammad Nikravesh May 03 '18 at 09:37
  • IL for decimal `==` : `call bool [mscorlib]System.Decimal::op_Equality(valuetype [mscorlib]System.Decimal, valuetype [mscorlib]System.Decimal)` – Sebastian L May 03 '18 at 09:52

1 Answers1

7

It is not necessary. Integer types are casted implicitly to decimal. You have to add the M suffix if the literal represents a floating point number. Floating point literals without a type suffix are double and those require an explicit cast to decimal.

decimal d = 1;     // works
decimal d2 = 1.0   // does not work
decimal d3 = 1.0M  // works

The literal 0 here is obviously a special case of the integer literal.

adjan
  • 13,371
  • 2
  • 31
  • 48
  • 1
    bit late to the party here; not neccessary, i know - but what you think about readability? in my application i added to every long/decimal/double/float value the specific suffix `l`/`m`/`d`/`f` - so I know with just seeing the value, what exact type it is. good idea? or too much? – Matthias Burger Jan 07 '20 at 08:45