I am working on someone else's code, and see things like:
if ((somevariable) > decimal.Parse("24,999.99")) ...
and
return int.Parse("0");
I cannot think of any logical reason to do this instead of
if ((somevariable) > 24999.99) ...
or
return 0;
What am I missing?
,
or .
L.B 2012-04-04 22:13
There is a semantic difference between the original code and your proposed change, but you're right in being skeptical.
The conversion from a string is just plain stupid, sorry. There is no need to do that, ever. The difference is that the original code parses the string as a decimal
, but your change would use a double
. So, it should be:
if (somevariable > 24999.99m) ...
decimal
type is implemented as C# is more of a hobby language for me, mostly when I need to whip up a Windows UI quickly. Thanks though, I'll fix that and do some reading - Ed S. 2012-04-04 22:14
For one thing, because 24999.99 is a double
value rather than a decimal
value - you would want to use 24999.99m
. But yes, otherwise it would be a much better idea to use the literal. (I wouldn't bother with the parentheses round the variable, either.)
Note that the code performing parsing will even fail if it's run in some cultures, where the decimal separator isn't .
and/or the thousands separator isn't ,
. I can't think of any good reason for using this.
You are not missing anything. That code is bogus. Refactor it the way you describe in the question.
For what it is worth, decimal.Parse("24,999.99")
will return 24999.99m
, a decimal
rather than 24999.99
, a double
. So the first excerpt should really be
if (somevariable > 24999.99m)
Of course, this assumes that the right hand operand in the comparison really should be a decimal
. Given the nature of this code, I would be doubtful of the correctness of everything.
Was the string within the parse really entered as a string literal, not as a variable?
If so, I would say this is just scary coding, I would only hope they did not put this within a hot spot function. It would then be a sign of a poor coder. I've heard some of those exist.
They may have wanted the benefit of seeing the comma that makes a number more readable. (which says: eeek! be warned about the rest of the code probably...)