Why you should use TryParse() in C#
Since .NET is strongly typed language you usually have to convert different strings into numbers when you receive input from the user. One way is to use int.Parse() and since you probably wont let your code break over a FormatException or even a OverflowException, then you add some sort of exception handling.
1 2 3 4 5 6 7 8 9 10 11 12 13 | int quantity; try { quantity = int.Parse(txtQuantity.Text); } catch (FormatException) { quantity = 0; } catch (OverflowException) { quantity = 0; } |
You are probably doing this a lot and I for one hate it, it is ugly. It seems like some of the people over in Redmond thinks the same, so they came up with this method instead int.TryParse() for .NET 2.0.
The great thing about this is that we now can reduce the code from above and make it much simpler (can also be done a little bit differently):
1 2 3 4 5 | int quantity; if (int.TryParse(txtQuantity.Text, out quantity) == false) { quantity = 0; } |
It tries to parse whatever value you put into it, and if it goes wrong TryParse() will return false and then the out parameter, will get some sort of default value (depending on the Datatype). If it successfully parses the string then the out parameter will get the result and the function will return true.
More about the keyword Out and the difference between it and Ref
The last great thing about this is, that if you have to do this a lot, TryParse() will actually save you a great deal of time because it doesn`t have to throw an exception.
Disclaimer: The example is very simple, but it displays the usage of the function. It doesn`t fit into every single context of how one would use it :)
You’re right, this is a great little function addition.
Unfortunately, from what I gather, the TryParse() method is not part of any interface, rather, type classes have implemented by convention more than anything else.
This is an annoyance when it comes to generics.
I would really like to be able to enfore that my generic’s type implements a TryParse() method… but can’t really find any nice way of doing this without wrapping all the existing type classes.
I’d appreciate any suggestions :)
C
A couple of points…
Why would you do
if (int.TryParse(txtQuantity.Text, out quantity) == false)
instead of
if (!(int.TryParse(txtQuantity.Text, out quantity))) {
Also, catching exceptions may not always be a bad thing to do. A well designed application may want to report this to the user or send an alert that the configuration is not setup in the db or whatever.
Hey Clay
Im not sure if there is a better approach then the one you mention :/
Hey S
The reason why I used False instead of the ! operator, is that I think it is more readable. I have occasionally seen people overlook the ! operator and therefore misunderstood what was going on. But you can use the ! operator if you want :)
You are right when you say that an application may want to report back to the user, but you still don`t need to catch an exception in this case or any other case where TryParse() is available.
Hi,
I don’t see why you can’t just leave as
if (int.TryParse(txtQuantity.Text, out quantity)){ … }
It is shorter and it’s more readable, at least to me.
Por qué deberÃas utilizar TryParse() en C#…
C# proporciona al programador una manera muy elegante para comprobar el tipo de un dato….
Actually the documentation says that if the number cannot be parsed, the method assigns 0 to the second parameter:
int quantity;
int.TryParse(txtQuantity.Text, out quantity);
So this is enough, you dont need assign 0 to quantity:
Public Shared Function TryParse(ByVal s As String, ByRef result As Integer) As Boolean
Parameters:
s: A string containing a number to convert.
result: When this method returns, contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed.
Hey Andres
Yep, thats right and im fully aware of it :)
But this is just an example of how TryParse() works and i could probably have done it a bit diffent, but i think i still gets message across..
Nice article. I learn alot of TryParse here. Save my life in my code Review.
Not sure why the world is giving you such a hard time about the “best way” to use TryParse. The article is short, sweet, and makes a well placed point on the issue. Thanks.
or it could be done even simpler than that on your examples…
int.TryParse(txtQuantity.Text, out quantity) ? quantity = 0 : quantity;
Regards, =)
Fernando, are you sure C# supports the ternary operator? I doubt it.
Yes, C# definitely supports the ternary operator:
http://msdn.microsoft.com/en-us/library/ty67wk28.aspx
Hi Anna and everybody else :)
I think the issue that Omotayo is having, is that when you use the ternary operator, then you should also have the statement return something.
ex.
int myVar = (blabla == true)? 0 : 1;
What Fernando is doing might seem a bit odd to people, because the expression isn’t fully valid and doing this “quantity = 0″ inside it, seems odd.
I think people goes wrong in the example where I evaluate the statement to check if it went Ok or not and then assign a zero to quantity (since zero is the fallback value if the false) But im just trying to prove a point.
I might have to clarify it a bit more at some point.
best regard,
Mark
int.TryParse(txtQuantity.Text, out quantity) ? quantity = 0 : quantity;
i agree with mark.
If I saw this during a review, i’d change it.
the original example is pretty close to best practice.
use TryParse in an ‘if’ statement…if the Parse fails you can return the default, set it to a known error value, i.e. -1, or throw an exception.
someone made the point about catching exceptions, and they’re correct.
this gives you control over the exception under this particular circumstance and can aid you considerably later
int id = int.TryParse(”200″, out id) ? id : -1;
Thanks for the advice! Nice comparison of 2 examples. i got some weird impression that you are rather biased to display the superiority of the latter example by making your 1st example stupid. ;p
int quantity;
try
{
quantity = txtQuantity.Text;
}
catch (Exception Ex)
{
quantity = 0;
}
That is the revised code of your 1st example and actually same as how the 2nd example works. Now this is a fairer comparision and i will see that 2nd example isn’t that miraclous. Maybe the OUT overload’s just synatic sugar, as i am unsure of the difference in performance. Maybe you can go further and demostrate the difference in performance.
^Ok, I had run both way in a loop 10000 times and tryParse is 175 times faster. Try Catch is an expensive process :S
Hi Chan
I thought that the link at the bottom of my article, then one that says “Benchmark Test”, kind of gave an impression of how well it performs?
anyway, if I was biased about the example then I would probably have added one more Catch to it ;P
I know that it might look like overkill and that you probably just as easily could use Exception. However, my rule of thumb is that you should only catch specific exceptions
http://fatagnus.com/back-to-basic-with-the-try-catch-statement/
The example is very simple, but it displays the usage of the function. It doesn’t fit into every single context of how one would use it :)
best regards
Mark
[...] him about it, but have a reputation to protect. Besides you could always look it up on Google to know what it is & if there is any performance benefit in doing [...]