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 more code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 6 |
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.
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.