Why c# decimals can't be initialized without the M suffix?
public class MyClass
{
public const Decimal CONSTANT = 0.50; // ERROR CS0664
}
produces this error:
error CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type
as documented. But this works:
public class MyClass
{
public const Decimal CONSTANT = 50; // OK
}
And I wonder why they forbid the first one. It seems weird to me.
The type of a literal without the m
suffix is double
- it's as simple as that. You can't initialize a float
that way either:
float x = 10.0; // Fail
The type of the literal should be made clear from the literal itself, and the type of variable it's assigned to should be assignable to from the type of that literal. So your second example works because there's an implicit conversion from int
(the type of the literal) to decimal
. There's no implicit conversion from double
to decimal
(as it can lose information).
Personally I'd have preferred it if there'd been no default or if the default had been decimal
, but that's a different matter...
The first example is a double literal. The second example is an integer literal.
I guess it's not possible to convert double to decimal without possible loss of precision, but it is ok with an integer. So they allow implicit conversion with an integer.
Every literal is treated as a type. If you do not chose the 'M' suffix it is treated as a double
. That you cannot implicitly convert a double
to a decimal
is quite understandable as it loses precision.
下一篇: 为什么没有M后缀,c#小数不能被初始化?