# Why you should use TryParse() in C#

Posted

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.

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):

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 doesnt have to throw an exception.

Benchmark test

Disclaimer: The example is very simple, but it displays the usage of the function. It doesnt fit into every single context of how one would use it :)

## 28 thoughts on “Why you should use TryParse() in C#”

1. Clay wrote:

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

2. S wrote:

A couple of points…

Why would you do
if (int.TryParse(txtQuantity.Text, out quantity) == false)
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.

3. Mark Jensen wrote:

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.

4. Tomas Kirda wrote:

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.

5. Pingback: programame.net

6. Andres - cx wrote:

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.

7. Mark Jensen wrote:

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..

8. PohEe.com wrote:

Nice article. I learn alot of TryParse here. Save my life in my code Review.

9. Thomas Evers wrote:

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.

• Steve Schmalfeld wrote:

Very nicely done. Short, sweet and to the point. As for the rest, well, everyone is a critic lol,

I appreciate the time you took to publish this. Thank you.

10. Fernando Lopez Jr. wrote:

or it could be done even simpler than that on your examples…

int.TryParse(txtQuantity.Text, out quantity) ? quantity = 0 : quantity;

Regards, =)

11. Omotayo Fakinlede wrote:

Fernando, are you sure C# supports the ternary operator? I doubt it.

12. Mark Jensen wrote:

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

13. anon wrote:

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

14. Chris wrote:

int id = int.TryParse(“200″, out id) ? id : -1;

15. chan kun juan wrote:

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.

16. chan kun juan wrote:

^Ok, I had run both way in a loop 10000 times and tryParse is 175 times faster. Try Catch is an expensive process :S

17. Mark Jensen wrote:

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

18. Mike Jensen wrote:

In response to Andres’ 2-year-old comment.
One good reason to test the boolean result of the TryParse function is that you might not want to assign zero if the input fails to parse: You might instead want to assign a NULL value, for example when setting a nullable database field.

Thanks for the article Mark.

19. BluePlateSpecial wrote:

Hopefully someone will see this and reply back even though this is an old article. I was wondering why this was happening. Given this code:

double.TryParse(“34.12345″, out doubleVar)

it seems that doubleVar becomes equal to 34.1234 instead of 34.12345. It seems as though TryParse (and probably Parse for that matter) cuts off some decimal places even though the type has plenty of space to hold them. This is a frustrating problem that seems like either a bug or a very bad design decision. Does anyone have any ideas on how to get TryParse to parse the string containing a number to as many decimal places as the string originally contains (and obviously as many as the type will allow)?

20. Dj Kav wrote:

TryParse is a much welcome and needed addition to validation.

Try/Catch is a last resort to things that can’t be handled with normal code. IE, connections and timeouts or other such critical errors.

If you need to use exception handling to try and convert a String into an Int then your being lazy in your validation code.

I can generate reports on the out come of TryParse without needing the Try/Catch exception handling.

Try/Catch is expensive in resources and should only be used sparingly. Not a replacement to proper validation code.

21. Matthew wrote:

I love TryParse() and use it in all of my code. I often write static TryParse() methods for my custom classes when complicated parsing is needed (such as converting a DataRow to a class). Some thing like: bool success = MyClass.TryParse(DataRow row, out MyClass myobj);

22. Tanner wrote:

Thanks! It was helpful for me because the implementation is different than the VB version.

23. MissCheeva wrote:

Sweet! It did exactly what it said on the tin. A nice and concise article regardless of the unhelpful other posts.

Thanks
Mark