what is the purpose of double implying?
for example:
const decimal dollars = 25.50开发者_运维问答M;
why do we have to add that M
?
why not just do:
const decimal dollars = 25.50;
since it already says decimal
, doesnt it imply that 25.50
is a decimal?
No.
25.50
is a standalone expression of type double
, not decimal
.
The compiler will not see that you're trying to assign it to a decimal
variable and interpret it as a decimal.
Except for lambda expressions, anonymous methods, and the conditional operator, all C# expressions have a fixed type that does not depend at all on context.
Imagine what would happen if the compiler did what you want it to, and you called Math.Max(1, 2)
.
Math.Max
has overloads that take int
, double
, and decimal
. Which one would it call?
There are two important concepts to understand in this situation.
- Literal Values
- Implicit Conversion
Essentially what you are asking is whether a literal value can be implicitly converted between 2 types. The compiler will actually do this for you in some cases when there would be no loss in precision. Take this for example:
long n = 1000; // Assign an Int32 literal to an Int64.
This is possible because a long
(Int64) contains a larger range of values compared to an int
(Int32). For your specific example it is possible to lose precision. Here are the drastically different ranges for decimal
and double
.
Decimal: ±1.0 × 10−28 to ±7.9 × 1028 Double: ±5.0 × 10−324 to ±1.7 × 10308
With knowledge it becomes clear why an implicit conversion is a bad idea. Here is a list of implicit conversions that the C# compiler currently supports. I highly recommend you do a bit of light reading on the subject.
Implicit Numeric Conversions Table
Note also that due to the inner details of how doubles and decimals are defined, slight rounding errors can appear in your assignments or calculations. You need to know about how floats, doubles, and decimals work at the bit level to always make the best choices.
For example, a double cannot precisely store the value 25.10, but a decimal can.
A double can precisely store the value 25.50 however, for fun binary-encoding reasons.
Decimal structure
精彩评论