2009-04-27

Using TryParse

I just figured out a way to use int.TryParse in an if-sentence.

string myInputString = myTextBox.Text;
int i = –1;
if(int.TryParse(myInputString, out i) && i > 0)
{

//do cool stuff

}

This only works with the “&&” operator. If the parse fails, the second part that uses the “out” parameter from the parse, will not be run.

8 comments:

  1. Hmmm... What if the string contains the number 0, or even a negative?

    ReplyDelete
  2. That's not the point I was trying to make. What the test after the "&&" is is not important. What I thought was a bit cool was that I could use the results of the parse directly in the same if-condition, both the boolean return value and the out parameters value, but only if the parse succeeded.

    ReplyDelete
  3. Yeah! Valid point!
    Btw. you don't have to/shouldn't set the value of i at all...

    ReplyDelete
  4. I agree. The code would be neater if I could do something like:

    if(int.TryParse(inputString, out int i) { ... }

    Declaring the 'i' and then using it in the scope of the 'if'. Alas, I dont think you can do that... yet. I shouldn't even have to declare the 'i' maybe, since it can be inferred from being the out parameter of an int.TryParse().

    ReplyDelete
  5. Hmm... I cannot edit comments for this blog. I tried to fix a typo in a comment by changing the post, but that introduced an inconsistency with previous comments. So the variable that now is called 'i' was previously called 'number'. Hope that clarifies everything :D

    ReplyDelete
  6. Your suggestion of declaring it inside the TryParse is even better (if you could do that, which you can't...)
    My point was about actually setting the i variable or not. (You shouldn't.)
    The usage will be:
    int i; //no assignment...
    if(int.TryParse(inputString, out i) && ...){...}

    ReplyDelete
  7. LOL for changing 'number' to 'i'... ;-)

    ReplyDelete
  8. Ok, point taken. I think maybe the compiler would have complained though, in earlier versions of VS, about the use of an unassigned variable... or maybe not? Maybe something to try in the lab :D

    ReplyDelete