I have noticed some people writing code like this to get a decimal in their code:
decimal amount = decimal.Parse("10.00");
It’s not that obvious, but you can write this which is better:
decimal amount = 10.00M;
If you don’t include the M then the compiler thinks you are typing a double which is why it won’t compile.
technorati tags: c#
And I certainly hope they are using decimal for a reason!! Say huge financial calculations to stop rounding problems or are they just sucking up the extra memory and taking a small performance hit for nothing.
http://wesnerm.blogs.com/net_undocumented/2004/03/decimal_perform.html
This is interesting, but you don’t find a lot of call for hard coded strings to be converted to decimal. The issue is that the ‘M’ won’t work if you are dealing with a variable, or even worse, a value from a DataRow column. xxxx.Parse(…) is used for changing variables and unknown strings to their appropriate numeric types. ‘M’ can’t be used with variables, which is where Parse is normally used, because you’d end up changing the variable name.
You wouldn’t ever use Parse for a known fixed string. I can’t imagine anyone writing decimal amount = decimal.Parse(“10.00”); when they would just write decimal amount = 10.00;
If they are doing as you suggest above, then they have much more serious problems than not knowing about the M.
@ Justin – it is financial related code … however doesn’t involve huge calculations so I’ve asked them to swap it all back to a double. Thanks for the link.
@ Rocky – the code snip I posted was a direct copy-paste from the actual codebase … there wasn’t a parameter being passed in or anything. Hence why I was scared!
Hmmm, Your example is wrong. The ‘M’ is at the start of the decimal value instead of the end.
decimal amount = M10.00;
Should be
decimal amount = 10.00M;
Cheers
@SonnyMal – Very astute. Thanks!
Please send me the code for decimal validation