Monday, July 29, 2013

Parse methods and what you need to know

We all need to parse one data type into another now and again. Parsing can cause your application to fail unexpectedly if you do it wrong. When parsing, you need to be aware what trouble you may get into.

Parsing, usually, comes in three flavors in .NET. I am going to focus on int/int32 parsing for the purpose of this entry. This can be applied to the other parsing utilities that .NET provides.


int.parse

  • Takes only strings for input.
  • Throws the following exceptions when it fails:
    • ArgumentNullException
    • FormatException
    • OverflowException

Convert.ToInt32

  • Has several overloads accepting various datatypes, and allows for a custom Format Provider if you want to supply one.
  • Throws the following exceptions when it fails.
    • FormatException
    • OverflowException
  • In addition, it allows passing of null values, however this means that it returns a 0 as the output value, and it also handles multiple datatypes to be converted into an integer.

int.TryParse

  • Takes only strings for input.
  • Requires an OUT parameter.
  • Does not throw exceptions, though if you provide Number Styles or a Format Provider those can cause exceptions themselves.
  • It will return a 0 as the output value as the method returns false, and it only accepts strings as input to convert.

Conclusion

Knowing that these three methods do very similar tasks, though hold their own specific behaviors, you should now be able to implement parsing in your application more effectively.
The right tool for the right job.

More can be found on MSDN about parsing and the parsing objects found here.

No comments:

Ajax Lesson

NOTE : This lesson uses jQuery as the interface for basic AJAX work. By no means is AJAX a product of jQuery and you do not need jQuery to ...