parse
Posted: Thu Apr 22, 2010 7:11 pm
I've always disliked .NET's "parse" and "tryParse" approach for parsing things like ints, floats and decimals. The "parse" method throws an exception if it can't parse (bleck) and the "tryParse" method typically requires a local var declaration (bleck):
What if parse returned a nilable type such as "int?", "float?" and "decimal?". Then you can just check the return value:
Which also means you could use the "coalesce" operator if you wanted a default value for unparseable input:
I don't see any disadvantages over the existing parse+tryParse unless you really need to distinguish the exceptions (overflow vs. bad input, for example).
Unfortunately, the name "parse" is already occupied by the .NET library, so we would need a to sue different name like "decimal.parseable(input)", or tweak the compiler so that this new .parse obscures the original one.
Feedback?
d as decimal
if decimal.tryParse(input, out d)
print 'safe to use d: [d]'
What if parse returned a nilable type such as "int?", "float?" and "decimal?". Then you can just check the return value:
d = decimal.parse(input)
if d, print 'safe to use d: [d]'
Which also means you could use the "coalesce" operator if you wanted a default value for unparseable input:
d = decimal.parse(input) ? 0.0
I don't see any disadvantages over the existing parse+tryParse unless you really need to distinguish the exceptions (overflow vs. bad input, for example).
Unfortunately, the name "parse" is already occupied by the .NET library, so we would need a to sue different name like "decimal.parseable(input)", or tweak the compiler so that this new .parse obscures the original one.
Feedback?