C# Foundations · Lesson 34

A validated stock summary

Combine parsing, guards, calculations, and reporting in one small program.

How it works

A small complete workflow makes the boundaries between earlier language features easier to see. Text enters the program, conversion decides whether it represents an integer, domain validation decides whether that integer is an acceptable quantity, and calculation updates a summary. Output is a final presentation step. Keeping these roles visible makes the program easier to test and extend.

This stock example accepts nonnegative quantities and counts malformed or negative inputs as rejected records. It deliberately treats zero as a valid observation. The total, accepted count, and rejected count answer different questions, so they are separate variables. A realistic application might also preserve a reason for each rejection, but even a compact example should avoid silently discarding the distinction.

Walk through the example. The input batch contains two positive quantities, a malformed label, a negative quantity, and zero. TryParse first checks conversion using invariant rules. The following range check rejects negative numbers. Only accepted quantities update the total and accepted count. The final report therefore shows three accepted records, two rejected records, and nine units in stock.

Watch the boundary. Do not update totals before all validation checks have passed. A later continue statement cannot undo an earlier addition. Also consider integer overflow when quantities or record counts can be large; the small sample does not establish a production limit. Choose explicit numeric bounds, checked arithmetic, or a wider total type as part of the business contract.

Practice independently. Extend the processor to distinguish malformed text from a negative quantity, with separate rejection counts for both reasons. Add an upper limit per record and test exactly that limit plus one. Extract conversion and validation into a function that returns success and a quantity. Finally run the same report for an empty batch and explain why all three counts are still well-defined.

A working example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;

int accepted = 0, rejected = 0, total = 0;
foreach (string text in new[] { "4", "bad", "-2", "0", "5" })
{
    if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int quantity) || quantity < 0)
    {
        rejected++;
        continue;
    }
    accepted++;
    total += quantity;
}
Console.WriteLine($"accepted:{accepted}");
Console.WriteLine($"rejected:{rejected}");
Console.WriteLine($"stock:{total}");

Expected output

accepted:3
rejected:2
stock:9
Try this
Convert, validate, and only then update the summary.