120

What is the difference between Parse() and TryParse()?

int number = int.Parse(textBoxNumber.Text);

// The Try-Parse Method
int.TryParse(textBoxNumber.Text, out number);

Is there some form of error-checking like a Try-Catch Block?

0

8 Answers 8

173

Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.

TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.

In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.

5
  • 2
    "internally the Parse method will call TryParse" Except that Parse pre-dates TryParse by several versions. Of course, they could have moved the core implementation to TryParse... Jan 22, 2009 at 1:10
  • 4
    @Joel - I assumed they would have moved the implementation, but I just had a look with reflector and they are separate implementations with exactly the same code other than one has 'throw ...' and one has 'return false'. I wonder why they aren't consolidated?!
    – Greg Beech
    Jan 22, 2009 at 8:39
  • 7
    Although, thinking about it, Parse throws a number of different exceptions so if all it had was a bool from TryParse then it wouldn't know which one to throw.
    – Greg Beech
    Jan 22, 2009 at 8:42
  • 6
    "use Parse if you are sure the value will be valid". I'd add, "but you acknowledge the possibility you might be wrong". If you were 100% sure it can parse, then you could just as correctly use TryParse which might be faster.
    – Jon
    Feb 15, 2013 at 12:42
  • 2
    And by "different exceptions", @GregBeech means the message, not the class. Apr 19, 2013 at 20:05
32

If the string can not be converted to an integer, then

  • int.Parse() will throw an exception
  • int.TryParse() will return false (but not throw an exception)
2
  • What if I use int.TryParse(some_method_that_throws_exception(), out int test)? Will it catch any exception or only the ones related to parsing? Nov 12, 2018 at 17:19
  • 2
    @AlexandruAntochi You should not ask a question as a comment. This will make it almost impossible for others to benefit from useful answers. However, to make it worth your while, the answer to your question is no, int.TryParse will not throw at all. If the method fail to parse, it will only reflect this by a return value of false. This makes it convenient to use if(int.TryParse… to only do something if the parse succeeds.
    – Rob
    Jan 23, 2019 at 17:00
4

The TryParse method allows you to test whether something is parseable. If you try Parse as in the first instance with an invalid int, you'll get an exception while in the TryParse, it returns a boolean letting you know whether the parse succeeded or not.

As a footnote, passing in null to most TryParse methods will throw an exception.

1
  • Passing null to basic types (int, double, DateTime, etc.) will NOT throw an exception Apr 11, 2018 at 16:53
4

TryParse and the Exception Tax

Parse throws an exception if the conversion from a string to the specified datatype fails, whereas TryParse explicitly avoids throwing an exception.

2
  • TryParse will throw an exception if you pass null in for most integral TryParse methods. Jan 22, 2009 at 9:47
  • 1
    Great link. I am surprised that no one hasn't yet started the "which one is best or which coding practice should be applied" discussion. Feb 14, 2010 at 16:06
0

TryParse does not return the value, it returns a status code to indicate whether the parse succeeded (and doesn't throw an exception).

1
  • 6
    TryParse does return the value through parameter two which is specified with the out keyword. Feb 14, 2010 at 16:00
0

For the record, I am testing two codes: That simply try to convert from a string to a number and if it fail then assign number to zero.

        if (!Int32.TryParse(txt,out tmpint)) {
            tmpint = 0;
        }

and:

        try {
            tmpint = Convert.ToInt32(txt);
        } catch (Exception) {
            tmpint = 0;
        }

For c#, the best option is to use tryparse because try&Catch alternative thrown the exception

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

That it is painful slow and undesirable, however, the code does not stop unless Debug's exception are settled for stop with it.

1
  • The first code snippit doesn't do anything, since tmpint will already be set to zero if the string is not able to be parsed as an int. Jun 29, 2015 at 15:06
0

I know its a very old post but thought of sharing few more details on Parse vs TryParse.

I had a scenario where DateTime needs to be converted to String and if datevalue null or string.empty we were facing an exception. In order to overcome this, we have replaced Parse with TryParse and will get default date.

Old Code:

dTest[i].StartDate = DateTime.Parse(StartDate).ToString("MM/dd/yyyy");
dTest[i].EndDate = DateTime.Parse(EndDate).ToString("MM/dd/yyyy");

New Code:

DateTime startDate = default(DateTime);
DateTime endDate=default(DateTime);
DateTime.TryParse(dPolicyPaidHistories[i].StartDate, out startDate);
DateTime.TryParse(dPolicyPaidHistories[i].EndDate, out endDate);

Have to declare another variable and used as Out for TryParse.

2
  • You don't need to initialize startDate and endDate as DateTime.TryParse will always overwrite them with DateTime.MinValue. If incorrect date representations should be converted to a different value, check the return value of DateTime.TryParse and if it is false, set the value explicitly.
    – Palec
    May 31, 2017 at 9:43
  • Using DateTime? (DateTime nullable)
    – Kiquenet
    Jun 10, 2017 at 17:55
-1

double.Parse("-"); raises an exception, while double.TryParse("-", out parsed); parses to 0 so I guess TryParse does more complex conversions.

1
  • 4
    But does TryParse return true or false? That's how you'll know if it was "valid". Apr 19, 2013 at 20:06

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.