-3

In the C# language, why would a decimal data type require an "m" at the end of the value? Would simply not just declaring the data type as 'decimal' be enough as is the case with other numeric data types such as 'int' or 'double'? (I'm new to this and am just curious as it seems to go against my own sense of logical behavior).

{
decimal variableName = 489872.76m; //<---
double variableName = 39.768;
int variableName = 14;
}
Craig
  • 1
  • Click on `decimal` and press `F1` – Franck Jun 17 '19 at 19:18
  • Okay, so Microsofts site says: "If you want a numeric real literal to be treated as decimal, use the suffix m or M. Without the suffix m, the number is treated as a double and generates a compiler error." Sure, that's all well and fine, but you've already stated that the variable is a decimal right at the beginning... It just seems a bit redundant. – Craig Jun 17 '19 at 19:23
  • You declared that the variable is `decimal` only. The `m` indicator acts on the *other side* of the assignment, which of course might take place much later. c# tends to not step in and do implicit conversions for you, thus the need for the indicator. There is a language with "robust" implicit conversions (and accompanying complications and bugs) - its name is Visual Basic – Ňɏssa Pøngjǣrdenlarp Jun 17 '19 at 19:51
  • 1
    The correct way to think about this is: the compiler is trying to catch your mistakes. Doubles and decimals are confusingly similar, and it is usually a bug to mix them. By requiring that you use the suffix, the compiler ensures that you are *thinking* about whether you mean to use decimal arithmetic or binary arithmetic. A fundamental design principle of C# is *C# aggressively tries to find your mistakes and tell you about them so you can fix them*. If you prefer a language that hides your mistakes, try VB or Javascript. – Eric Lippert Jun 17 '19 at 20:47
  • 2
    You note that this is redundant. Of course it is redundant by design! **The right quantity of redundancy is good in a programming language**. That's what allows programming languages to be (1) understood by humans, and (2) checked for errors. – Eric Lippert Jun 17 '19 at 20:48

1 Answers1

0

If you want a numeric real literal to be treated as decimal, use the suffix m or M

for examble 20.2 can be float or decimal then you can specify type of that with m or M

You can find out more at What does the "M" stand for in decimal value assignment?

And also check this docs from microsoft

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/decimal

Mohammad Ansari
  • 1,076
  • 1
  • 11
  • 22