views:

58

answers:

1

Hey all,

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!

+13  A: 

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.

Matthew Whited
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)
Matthew Whited
@Matthew: Entirely correct answers should get many many more. I hope to see it yet higher. ;)
Lance May
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 :)
Matthew Whited
yes! TryParse. Thanks a ton sir, been trying to remember this all morning. Much appreciated!
bwerks
Also upcount is now 11! Sounds like a lot of people might have been unaware. :D Hooray for continuous learning
bwerks
lol... I'm glad I could help someone. Pretty nice when you get major upvotes on some of thes questions... makes the lack of upvotes of other questions not bug ya so much :)
Matthew Whited