Skip to content

Parsing and Validating

The Course
•
25 min study

To do arithmetic on input, you must convert it from text. There are two ways. int.Parse throws an exception when the text isn't a number. int.TryParse returns false instead, which is usually what you want, since bad input is an ordinary event and not an emergency.

Parse and TryParse

TryParse has the same shape as TrySplit from Day 3 and TryGetValue from Day 4: a bool says whether it worked, and an out variable carries the value. When it fails, the out variable is 0, so don't use the number until you've checked.

The same text, two ways C#
Console.WriteLine(int.TryParse("25", out int good));
Console.WriteLine(good);

Console.WriteLine(int.TryParse("ten", out int bad));
Console.WriteLine(bad);

Console.WriteLine(int.Parse("ten"));
Check your prediction
Text
True
25
False
0
Unhandled exception. System.FormatException

Numbers can be valid to TryParse and still be wrong for your program. "-5" and "+25" both parse fine, and even "99999999999" fails only because it's too large for an int. A type check isn't the same as a rule, so test the range afterwards.

What counts as a number? C#
foreach (string text in new[] { "25", " 25 ", "+25", "-5", "2.5", "", "99999999999" })
{
    bool ok = int.TryParse(text, out int value);
    Console.WriteLine($"[{text}] {ok} {value}");
}
Check your prediction
Text
[25] True 25
[ 25 ] True 25
[+25] True 25
[-5] True -5
[2.5] False 0
[] False 0
[99999999999] False 0

Splitting a line into fields

Split with a count limits how many pieces you get, and the last piece keeps the rest of the text. That's just right for a format in which a title, which can contain spaces, comes last. Always check how many parts came back before reading them.

Limit the pieces C#
string[] all = "25 0 Read a chapter".Split(' ');
string[] three = "25 0 Read a chapter".Split(' ', 3);
string[] short_ = "25".Split(' ', 3);

Console.WriteLine(all.Length);
Console.WriteLine(three.Length);
Console.WriteLine(three[2]);
Console.WriteLine(short_.Length);
Check your prediction
Text
5
3
Read a chapter
1

Return null for bad input

A parsing method needs a way to say "no result". With nullable checking on, a return type of StudyTask? says precisely that, and the compiler makes the caller deal with the null. The method checks each rule in turn and leaves as soon as one fails. Only when all of them have passed does it build the task.

Validate, then construct C#
#nullable enable

int rejected = 0;
string? line;
while ((line = Console.ReadLine()) is not null)
{
    StudyTask? task = Parse(line);
    if (task is null)
    {
        rejected++;
        continue;
    }
    Console.WriteLine(task);
}
Console.WriteLine($"Rejected: {rejected}");

static StudyTask? Parse(string line)
{
    string[] parts = line.Split(' ', 2);
    if (parts.Length != 2 || !int.TryParse(parts[0], out int minutes))
    {
        return null;
    }
    if (minutes < 1 || minutes > 180)
    {
        return null;
    }
    return new StudyTask(parts[1], minutes);
}

record StudyTask(string Title, int Minutes);
25 Read abc Read 0 Rest 45 Write notes
Check your prediction
Text
StudyTask { Title = Read, Minutes = 25 }
StudyTask { Title = Write notes, Minutes = 45 }
Rejected: 2

A bad line doesn't stop the program. It's counted and the loop continues, so one typo doesn't lose the valid lines after it. Add your own bad lines to the box, such as 200 Long, a blank line and a line with only a number.

Going further: decimals and culture

Different countries write numbers differently: 1,5 in much of Europe means 1.5. On a local machine, double.TryParse and decimal.TryParse follow the computer's language settings, so the same text can give different results on different machines. For data files, say what you mean with decimal.TryParse(text, System.Globalization.CultureInfo.InvariantCulture, out decimal value). The browser runtime uses invariant settings already, and whole numbers don't have this problem.

Your turn

Exercise

Parse a score line

Input lines look like Ada 72: a name and a whole-number score from 0 to 100. Write Parse(string line), which returns a record Score(string Name, int Points) or null. Read every line of input, print the valid scores, and finish with Average: 61.0 and Rejected: 2. If nothing is valid, print Average: 0.0.

Your workspace C#
#nullable enable

string? line = Console.ReadLine();
Console.WriteLine(line);
Ada 72 Grace 50 Linus 101 noscore
Hint 1: the idea

Parsing, validating and averaging are three separate jobs. Rejected lines must not affect the count or the total used by the average.

Hint 2: a first step

Write Parse and call it from a loop that only prints the result, before you add any totals.

Show one solution
C#
#nullable enable

int rejected = 0;
int total = 0;
int count = 0;

string? line;
while ((line = Console.ReadLine()) is not null)
{
    Score? score = Parse(line);
    if (score is null)
    {
        rejected++;
        continue;
    }
    Console.WriteLine($"{score.Name}: {score.Points}");
    total += score.Points;
    count++;
}

double average = count == 0 ? 0 : (double)total / count;
Console.WriteLine($"Average: {average:F1}");
Console.WriteLine($"Rejected: {rejected}");

static Score? Parse(string line)
{
    string[] parts = line.Split(' ');
    if (parts.Length != 2 || !int.TryParse(parts[1], out int points))
    {
        return null;
    }
    if (points < 0 || points > 100)
    {
        return null;
    }
    return new Score(parts[0], points);
}

record Score(string Name, int Points);
Text
Ada: 72
Grace: 50
Average: 61.0
Rejected: 2

Parse returns null for any line it can't use, so the loop has a single test for every kind of bad line. TryParse reports failure instead of throwing, which suits input where bad lines are expected. The average checks count == 0 before dividing: with no valid lines, (double)total / count would be 0.0 / 0, which gives NaN (not a number) rather than 0.

Run the solution with an empty input box and with input where every line is bad. Without the count == 0 guard, what would (double)total / count print?

Was this article helpful?

Your response is saved on this device.