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.
Hmmm... What if the string contains the number 0, or even a negative?
ReplyDeleteThat'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.
ReplyDeleteYeah! Valid point!
ReplyDeleteBtw. you don't have to/shouldn't set the value of i at all...
I agree. The code would be neater if I could do something like:
ReplyDeleteif(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().
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
ReplyDeleteYour suggestion of declaring it inside the TryParse is even better (if you could do that, which you can't...)
ReplyDeleteMy 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) && ...){...}
LOL for changing 'number' to 'i'... ;-)
ReplyDeleteOk, 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