2

In the pursuit of elegant coding, I'd like to avoid having to catch an exception that I know well may be thrown when I try to validate that the Text field of a Textbox is an integer. I'm looking for something similar to the TryGetValue for Dictionary, but the Convert class doesn't seem to have anything to offer except exceptions.

Are there any that can return a bool for me to check?

To be clear, I'd like to avoid doing this

TextEdit amountBox = sender as TextEdit;
if (amountBox == null)
    return;
try
{
    Convert.ToInt32(amountBox.Text);
}
catch (FormatException)
{
    e.Cancel = true;
}

in favor of something like this:

TextEdit amountBox = sender as TextEdit;
if (amountBox == null)
    return;
e.Cancel = !SafeConvert.TryConvertToInt32(amountBox.Text);

Thanks!

1 Answer 1

13

int.TryParse is your friend...

TextEdit amountBox = sender as TextEdit; 
if (amountBox == null) 
    return; 
int value;
if (int.TryParse(amountBox.Text, out value))
{
    // do something with value
    e.Cancel = false;
}
else 
{
    // do something if it failed
    e.Cancel = true;
}

... By the way, most of the privitive value types have a static .TryParse(...) method that works very similar to the sample above.

6
  • Wow... thanks guys!... I just looked away for a minute to write up an example and when I got back I had 5 upvotes... sweet :o) Jun 17, 2010 at 13:27
  • @Matthew: Entirely correct answers should get many many more. I hope to see it yet higher. ;)
    – Lance
    Jun 17, 2010 at 13:31
  • I got 5+ upvotes when it just said "int.TryParse is your friend" I really expected that I should have a better descriptiong than that... but hey, whatever works :) Jun 17, 2010 at 13:33
  • yes! TryParse. Thanks a ton sir, been trying to remember this all morning. Much appreciated!
    – bwerks
    Jun 17, 2010 at 14:14
  • Also upcount is now 11! Sounds like a lot of people might have been unaware. :D Hooray for continuous learning
    – bwerks
    Jun 17, 2010 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.