Parse or TryParse? Which one should I use?

Parse or TryParse? Which one should I use?


It's often require to parse a string value to another data type, like integer, and there exists a confusion among the developers whether to use the Parse method or the TryParse method that the framework provides to us.

 

In this post, we will discuss the difference between each of those two methods and guide you to understand and pick the preferable one. Continue reading to know more.

 

Parse or TryParse? Which one should I use?

 

It's a common interview question to ask a developer the difference between the int.Parse and int.TryParse methods. In most of the cases, I noticed that the developers get confused while answering this question. I often seen, while reviewing the code, people uses the int.Parse as it directly returns the value. But, there could be cases when the said method will fail and throw Exception. Let's discuss in more detail.

 

As the name itself says that the Parse method parses the string to return you the value, whereas the TryParse first tries to parse it and returns the original value if it succeeds. First one takes a single parameter as string and the other takes two parameters: one as an input string and the other as the out value. If TryParse succeeds, it returns true and provides you an option to check whether the parsing was successful.

Let's learn about int.Parse(...)

It's a common tendency to call the int.Parse(...) method to parse a string to an integer. But wait! Did you ever check what happens when you pass a null, any invalid string or a large number? Let's discuss each one of them, so that, you can get a clear understanding.

 

When you pass a null string as input parameter to int.Parse(...), it will throw you an ArgumentNullException:

 

string value = null;
int outValue = int.Parse(value); // throws ArgumentNullException
 

 

When you pass a correct integer value as string, it will parse it and return you the value:

 

string value = "999";
int outValue = int.Parse(value); // works fine, returns 999
 

 

When you pass a double value as string, instead of an integer, the outcome of it is a FormatException:

 

string value = "999.99";
int outValue = int.Parse(value); // throws FormatException
 

When it is unable to parse the string (like the below text) to integer, a FormatException will trigger:

 

string value = "kunal";
int outValue = int.Parse(value); // throws FormatException
 

 

When you pass a very large integer value as string to the method, it will throw OverflowException as it can't parse it to integer:

 

string value = "9999999999999999";
int outValue = int.Parse(value); // throws OverflowException
 

Let's learn about int.TryParse(..., ...)

Unlike the Parse method, int.TryParse(..., ...) does not directly return you the value. Instead, it returns whether the parsing was successful or not. The second parameter passed to this method is an out parameter, that gets filled by the method with the parsed value.

 

When you pass a null value to TryParse, instead of throwing ArgumentNullException, it returns false and fills the out value to '0' (zero):

 

string value = null;
int outValue = 0;
bool status = int.TryParse(value, out outValue); // outValue = 0
Console.WriteLine("Status: {0}, Value: {1}", status, outValue);
 

 

When you pass a correct integer value as string, it returns true and fills the out value with the parsed result:

 

string value = "999";
int outValue = 0;
bool status = int.TryParse(value, out outValue); // outValue = 999
Console.WriteLine("Status: {0}, Value: {1}", status, outValue);
 

 

Passing a double, does not throw FormatException. Rather, it returns false and fills the out value with '0' (zero):

 

string value = "999.99";
int outValue = 0;
bool status = int.TryParse(value, out outValue); // outValue = 0
Console.WriteLine("Status: {0}, Value: {1}", status, outValue);
 

 

Similarly, if you pass a non-integer value, it returns false and fills out value with '0' (zero):

 

string value = "kunal";
int outValue = 0;
bool status = int.TryParse(value, out outValue); // outValue = 0
Console.WriteLine("Status: {0}, Value: {1}", status, outValue);
 

 

When you pass a large integer number as string, which it can't parse, will return false instead of throwing OverflowException and will fill the out value with '0' (zero):

 

string value = "9999999999999999";
int outValue = 0;
bool status = int.TryParse(value, out outValue); // outValue = 0
Console.WriteLine("Status: {0}, Value: {1}", status, outValue);
 

 

Based on the returned value, you can check whether the parsing was successful. If succeeded, you can use the out value in subsequent lines of code. A point to note that, you need to initialize the out value before passing it to the TryParse method.

End Note

I hope that, you understood the difference between Parse and TryParse methods from the above post. Which one do you prefer now while writing code to parse a numeric string to number? It's TryParse method, for sure! Do let me know, if you still have any doubts/queries.

 

Another point to note that, it's applicable to all conversion from string to integer, double, long etc. For example: if you want to parse a string to double, call double.TryParse(..., ...); to convert a string to long, call long.TryParse(..., ...) similarly.

 

 



If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

4 comments

  1. this is very much helpful to me.

    ReplyDelete
  2. I wish you would have digged a little deeper than just the callings and results.

    What is the cost of an exception?
    Do you need the kind of error during parsing to give a message to the user? Like please only input numbers or please only input an integer value. etc.

    Does the fine-grained type of error justify the cost of an exception?

    And by "cost of exception" I am not talking about a SINGLE occurrance, but rather a backend where thousands of messages are received per second. An exception always generates a stack trace and unwinds the stack, so there is some overhead involved.

    And last but not least: How about checking the number by usage of an regular expression before doing an int.parse?

    ReplyDelete
    Replies
    1. That's very good point Andreas. Yes, cost of an exception is high, which, Parse() method generates. Better to always use TryParse() wherever possible.

      Delete
  3. Exceptions should be exceptional. If an invalid value is an expected outcome, e.g. user input, use TryParse. If an invalid value is truly exceptional, e.g. reading from a file in a well defined format, then use Parse.

    ReplyDelete

 
© 2008-2017 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top