dotnet 5: Decimal silently truncated - how to make it break?

Viewed 47

The following is done with .Net 5:

The following line is not allowed by the compiler as the number exceeds the maximum long value:

long value = 123456789123456789123456789123456789; // <= Not allowed by compiler

However, the following line is allowed by both the compiler and by the runtime:

Decimal value = 123456789123456789.123456789123456789m; // No compile time error, no runtime error.

The issue is, that the value is immediately truncated into 123456789123456789,12345678912. So the value is actually altered without any notice.

I would like to know if dotnet can be set up to blow up in this case as I want things to break early, at compile time at best or at least at runtime.

Anyone one out there who solved this?

1 Answers

This is by design.

From the C# specification:

A real literal suffixed by M or m is of type decimal. For example, the literals 1m, 1.5m, 1e10m, and 123.456M are all of type decimal. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding. Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal 2.900m will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.

I'm afraid your only option would be to build a Code Analyzer that would mark an error on such a line.

Related