Parsing text into values

Parsing is the other direction of the previous lesson: text becomes a number or a date. Every numeric type has a Parse that throws and a TryParse that answers a boolean, and both take a culture when the text uses separators.

Parse and the culture

int.Parse of a plain run of digits needs no culture. A thousands separator does: 1.234 is one thousand two hundred and thirty-four in German and one and a bit in the invariant culture, so the call has to say which one it means:

using System.Globalization; var german = new CultureInfo("de-DE"); Console.WriteLine(int.Parse("42")); Console.WriteLine(int.Parse("1.234", NumberStyles.AllowThousands, german)); Console.WriteLine(double.Parse("1,5", german)); Console.WriteLine(decimal.Parse("1.234,56", german)); Console.WriteLine(int.TryParse("12x", out var bad)); Console.WriteLine($"bad {bad}");

dotnet run

42
1234
1.5
1234.56
False
bad 0

The German decimal comma became a point in the value, and the grouping dot disappeared from the number. A failed TryParse leaves the output variable at its default, which is 0 for an int, and returns false instead of throwing.

NumberStyles

The style is the set of characters the parser may accept. The default for an integer is Integer, which allows a sign and whitespace but no separator; a decimal number allows a point. The program asks for thousands and a decimal point explicitly:

using System.Globalization; var styles = NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint; Console.WriteLine(int.TryParse("1,234", styles, CultureInfo.InvariantCulture, out var thousands)); Console.WriteLine(thousands); Console.WriteLine(int.TryParse("1.234", styles, CultureInfo.InvariantCulture, out var point)); Console.WriteLine(point); Console.WriteLine(int.TryParse("1.234", styles, new CultureInfo("de-DE"), out var german)); Console.WriteLine(german);

dotnet run

True
1234
False
0
True
1234

The first call read the comma as a thousands separator because the invariant culture says so. The second failed: the style allows a decimal point but the target is an int, and a value with a fractional part does not fit. The third read the same text as German, where the dot is the group separator.

FormatException and OverflowException

Parse reports two different failures with two different types. The text that is not a number throws FormatException; the digits that do not fit throw OverflowException:

try { int.Parse("12x"); } catch (FormatException e) { Console.WriteLine($"format {e.GetType().Name}"); Console.WriteLine($"message {e.Message}"); } try { int.Parse("99999999999"); } catch (OverflowException e) { Console.WriteLine($"overflow {e.GetType().Name}"); } Console.WriteLine("after the catches");

dotnet run

format FormatException
message The input string '12x' was not in a correct format.
overflow OverflowException
after the catches

The text of the first message names the input, which is why a parse error of a user value is worth catching and reporting with its own words. The second failure is a number of eleven digits, and an int holds at most ten; the catch is a different type, so a program that catches only FormatException would crash on this input.

TryParse

TryParse is the form for input that may be wrong: it returns a boolean and writes the value through an out parameter. It never throws for bad text, which makes it the right call in a loop over lines of a file:

using System.Globalization; var parsed = DateTime.TryParseExact( "10/03/2024", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date); Console.WriteLine($"exact {parsed} {date:yyyy-MM-dd}"); var loose = DateTime.TryParse("2024-03-10", out var any); Console.WriteLine($"loose {loose} {any:yyyy-MM-dd}"); Console.WriteLine(double.TryParse("3.5", NumberStyles.Float, CultureInfo.InvariantCulture, out var number)); Console.WriteLine($"number {number}"); Console.WriteLine(bool.TryParse("TRUE", out var flag)); Console.WriteLine($"flag {flag}");

dotnet run

exact True 2024-03-10
loose True 2024-03-10
True
number 3.5
True
flag True

TryParseExact takes the format the text must have, which is how a protocol pins its date format; TryParse accepts the formats of the culture and is convenient for a human input. bool.TryParse accepts the words in any case, which the last line shows. Next lesson takes the same strings apart as paths.

Exercises

  1. Parse a list of ten lines, count the ones that are numbers and print the sum of the rest as an error count.
  2. Parse 1,234.56 with the invariant culture and then as German; explain both results.
  3. Read int.MaxValue from text and then one more, and catch the overflow.
  4. Parse a date in ISO form with TryParseExact and try the same text with an American format.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which call reports a bad number as a boolean instead of an exception?

    Answer

    int.TryParse

    TryParse returns false and leaves the out value at its default.

  2. What is the second parameter of int.TryParse?

    Answer

    An out variable that receives the value

    The text and the out value are the required pair; a culture is optional.

  3. What does this program print? int.TryParse("12", out var n); Console.WriteLine(n);

    Answer

    12

    The out variable holds the parsed number, not the boolean.

  4. What does this program print? Console.WriteLine(int.Parse(" 42 "));

    Answer

    42

    The default integer style allows leading and trailing whitespace.

  5. What does NumberStyles.AllowThousands permit?

    Answer

    Group separators inside the number

    The measured German text 1.234 was read as 1234 with that style.

  6. Which exception does int.Parse("12x") throw?

    Answer

    FormatException

    The text is not a number, and the measured message said so.

  7. Which exception does a number too large for int throw?

    Answer

    OverflowException

    The digits are valid and the value does not fit, which is an overflow.

  8. What does this program print? Console.WriteLine(double.TryParse("abc", out var d));

    Answer

    False

    The text is not a number, so TryParse answers false.

  9. What does DateTime.TryParseExact require?

    Answer

    An exact format string for the text

    The measured call fixed the format as dd/MM/yyyy.

  10. What does this program print? using System.Globalization; Console.WriteLine(int.Parse("1F", NumberStyles.HexNumber, CultureInfo.InvariantCulture));

    Answer

    31

    The hexadecimal digits 1F are thirty-one in decimal.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev