C# Record Parser Project
Define a small text grammar and return a complete accepted record instead of partially modifying caller state.
Your brief
The lab format is one code, one vertical bar and a positive decimal place count from one through twenty. Codes contain non-whitespace text and no vertical bar. Numeric whitespace and signs are rejected. This is a deliberately small format, not a complete CSV parser. Return null on rejection and construct an owned record only after the whole input has passed. A real importer needs transport size limits and useful error details in addition to the parser’s local grammar.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Worked solution
Show the worked solution
using System;
using System.Globalization;
internal static class Program
{
private static void Main(string[] args)
{
BookingRecord? record = ParseRecord("W-17|3");
if (record is null) throw new InvalidOperationException("Fixture rejected");
Console.WriteLine($"{record.Code}: {record.Places}");
Console.WriteLine($"Junk accepted: {ParseRecord("W-17|3x") is not null}");
}
internal static BookingRecord? ParseRecord(string? line)
{
if (line is null) return null;
string[] fields = line.Split('|');
if (fields.Length != 2 || string.IsNullOrWhiteSpace(fields[0])) return null;
foreach (char c in fields[0]) if (char.IsWhiteSpace(c)) return null;
if (!int.TryParse(fields[1], NumberStyles.None, CultureInfo.InvariantCulture, out int places) || places is < 1 or > 20) return null;
return new BookingRecord(fields[0], places);
}
}
internal sealed record BookingRecord(string Code, int Places);
Expected result
W-17: 3
Junk accepted: False
Split rejects extra fields through the exact length check. The code and count are validated before constructing the result. Strings are immutable owned managed references, so the returned record does not borrow a temporary character buffer. The parser can allocate for an oversized line, so keep this teaching method behind a bounded input boundary in a production ingestion path.
Extend and test
Test null, empty input, missing and extra separators, blank or spaced codes, count zero, count twenty-one, leading signs and excessive numeric magnitude.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.