The C# core: a validator and a pricing function

The core is one static class and one record. It parses the request line, validates the three values, prices the order and formats the answer. It references nothing outside the base class library: the culture, the decimal type and the string methods are all in the runtime that every .NET program has.

The project

A class library is a project with no entry point, and this one is six lines of project file and no package:

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> </Project>

The core

The public method is Process, and it takes the line and returns the answer as a string, so every caller of the next pages gets the same text. The parse is one pass over three pairs:

using System.Globalization; namespace Core; public static class Pricing { private const decimal TaxRate = 0.20m; public static string Process(string line) { if (!TryParse(line, out var request, out var error)) { return $"err {error}"; } var subtotal = Math.Round(request.Quantity * request.Unit, 2, MidpointRounding.AwayFromZero); var tax = Math.Round(subtotal * TaxRate, 2, MidpointRounding.AwayFromZero); var total = subtotal + tax; return FormattableString.Invariant($"ok {subtotal:F2} {tax:F2} {total:F2}"); } private static bool TryParse(string line, out Request request, out string error) { request = default; error = ""; var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 3) { error = "format expected sku= qty= unit="; return false; } string? sku = null; var quantity = 0; var unit = 0m; foreach (var part in parts) { var index = part.IndexOf('='); if (index <= 0) { error = "format expected key=value"; return false; } var key = part[..index]; var value = part[(index + 1)..]; switch (key) { case "sku": sku = value; break; case "qty" when int.TryParse(value, out var parsed): quantity = parsed; break; case "unit" when decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out var parsed): unit = parsed; break; default: error = $"value {key}"; return false; } } if (sku is null || sku.Length is < 1 or > 20 || !sku.All(char.IsAsciiLetterOrDigit)) { error = "sku must be 1 to 20 letters or digits"; return false; } if (quantity is < 1 or > 100) { error = "qty must be 1 to 100"; return false; } if (unit is < 0.01m or > 10000m) { error = "unit must be 0.01 to 10000"; return false; } request = new Request(sku, quantity, unit); return true; } public readonly record struct Request(string Sku, int Quantity, decimal Unit); }

The method never throws for a bad line: a request that a user can send is not an exceptional condition, and an exception would turn an input mistake into a process failure in every caller. The failures are values of the protocol, which is why the three callers of this group share one error format.

Money and rounding

The build

A class library has no Main, so its check is the build and its tests. The build of this one, in Release, on this container:

dotnet build src/Core/Core.csproj -c Release -nologo -v:q
echo "status: $?"


Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:02.79
status: 0

The output is a dll that the three hosts of the next pages reference. The pages that follow do not repeat the code: they show the project that references this one and the command that runs it, which is the same shape as the class library lesson of the C# course (lesson 101).

The next page is the first caller: a Python service that runs a program which uses this library once per request.

Exercises

  1. Change the tax rate to a constant of the protocol and check the answers of the test table.
  2. Add a validation rule that the sku must not start with a digit.
  3. Make the total round once at the end and find a request where the answer differs from the current one.
  4. Replace the record with a struct and explain whether the core notices.

Questions

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

  1. What does the core return for a bad line?

    Answer

    A value of the protocol, an err line, and never an exception

    The three callers share the error format because of it.

  2. Why is the amount a decimal and not a double?

    Answer

    A decimal is base-10, so 1.50 is exact

    The money rule needs exact cents.

  3. What does this program print? var total = 2 * 1.50m; Console.WriteLine($"{total:F2}");

    Answer

    3.00

    Two at 1.50 is three, formatted with two decimals.

  4. Why is the subtotal rounded before the tax?

    Answer

    So the lines of the answer add up to the total

    Rounding once at the end breaks the invoice arithmetic.

  5. What does this program print? Console.WriteLine(Math.Round(0.125m, 2));

    Answer

    0.12

    The default of Math.Round is ToEven, which rounds 0.125 to 0.12.

  6. Which rounding does the core choose?

    Answer

    AwayFromZero

    It is a business rule and the code names it.

  7. What does this program print? Console.WriteLine(Math.Round(0.125m, 2, MidpointRounding.AwayFromZero));

    Answer

    0.13

    MidpointRounding.AwayFromZero turns 0.125 into 0.13.

  8. Why is the answer formatted with the invariant culture?

    Answer

    So the point is the separator on every machine

    A caller in another locale must get the same three numbers.

  9. What does this program print? var qty = 0; Console.WriteLine(qty is < 1 or > 100 ? "err qty must be 1 to 100" : "ok");

    Answer

    err qty must be 1 to 100

    Zero is outside the range, which is the rule of the protocol.

  10. What is the output of the class library build?

    Answer

    A dll that the hosts reference

    The build output is the dll of the core.

The C# code on this page was built with the .NET SDK 10.0.303 and the Python code was run with Python 3.14.10, on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.

Article author: Arthur Isaev