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 amounts are decimal and not double. A decimal is a base-10 number, so 1.50 is 1.50 and not the nearest binary fraction; the C# course measures the difference in lesson 015.
- The subtotal is rounded to the cent before the tax is computed, and the tax is rounded again. Rounding once at the end would produce a total that does not match the two lines above it on an invoice.
- MidpointRounding.AwayFromZero is a business rule and not a default: the default of Math.Round is ToEven, which turns 0.125 into 0.12. A finance team must decide this, and the code must say which one it chose.
- The answer is formatted with FormattableString.Invariant, so the decimal separator is a point and the answer does not depend on the culture of the machine that runs the core.
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
- Change the tax rate to a constant of the protocol and check the answers of the test table.
- Add a validation rule that the sku must not start with a digit.
- Make the total round once at the end and find a request where the answer differs from the current one.
- 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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
Which rounding does the core choose?
Answer
AwayFromZero
It is a business rule and the code names it.
-
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.
-
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.
-
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.
-
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