When I try to declare a variable like this:
decimal order = 5.0;
I get the error message "Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a liter of this type."
Can someone explain why the M is needed?
Any numeric literal with a decimal point but no suffix is of type double
. From the C# 5 specification, section 2.4.4.3:
If no real-type-suffix is specified, the type of the real literal is
double
. Otherwise, the real type suffix determines the type of the real literal, as follows: [...]
There's no implicit conversion from double
to decimal
, so trying to assign a double
value to a decimal
variable fails.
You'd get the same thing if you wanted a float
value:
float x = 5.0; // Nope, same problem
You could explicitly cast to float
or decimal
, but that would be a bad idea for float
and a very bad idea for decimal
.
See more on this question at Stackoverflow