Skip to content
LumenaryAcademy
Professional 70 min

The ecosystem and a complete project

NuGet, ASP.NET Core, testing with xUnit, formatters and analyzers, and a small program written the way a team would write it.

Code tested · 2AI-draftedAwaiting review by a computer scientist
MotivationH

A language is a community of tools

Nobody ships C# alone. A typical service uses a web framework, a database library, a logging library, a JSON serialiser (that one is built in), a test framework and a dozen smaller packages, built by one SDK, checked by analyzers, formatted by a formatter, and run by continuous integration on every change. Knowing the language is necessary; knowing this ecosystem is what makes you productive on a team.

This lesson surveys that ecosystem as a working C# developer meets it, then builds a complete small program, a trip expense splitter, written in the style of everything this course has taught, with its tests.

DefinitionsH

NuGet: packages and dependencies

Definition— NuGet package

A versioned, zipped bundle of compiled assemblies (and sometimes analyzers, build logic or native libraries) published to a feed, usually the public gallery at nuget.org. A project lists the packages it needs, and dotnet restore (run automatically by build, run and test) downloads them and everything they depend on.

You add a package with the CLI, which writes a PackageReference into the project file:

bash
dotnet add package Serilog --version 4.2.0
dotnet list package --outdated
dotnet list package --vulnerable
xml
<ItemGroup>
  <PackageReference Include="Serilog" Version="4.2.0" />
</ItemGroup>

Habits that keep dependencies healthy:

  • Fewer is better. Each package is code you did not write but must trust and update. Before adding one, check whether the base class library already does the job: JSON (System.Text.Json), HTTP (HttpClient), logging abstractions, dependency injection, configuration and much more are built in.
  • Check what you depend on: who maintains it, its licence, how recently it was updated. NuGet audits restores against a database of known vulnerabilities and warns about vulnerable packages (on by default since .NET 8).
  • Manage versions in one place. In a solution with many projects, central package management (a Directory.Packages.props file at the root) sets each package's version once for all of them.
  • Update deliberately and often, with tests to tell you whether an update broke something. Tools such as Dependabot or Renovate open pull requests for updates automatically.

A single-file app declares packages with a directive instead (#:package Serilog@4.2.0), which dotnet project convert turns into the same PackageReference.

ExplanationH

The major frameworks

You will not learn these in a single lesson, but you should know what each is for and what its code looks like.

ASP.NET Core is the web framework: HTTP APIs, server-rendered pages, real-time connections (SignalR) and gRPC services, on a fast cross-platform server called Kestrel. A web API with one endpoint fits in a few lines. This sketch is a file-based app (the #:sdk directive selects the web SDK); the IExchangeRates interface and its FixedRates implementation are left out:

csharp
#:sdk Microsoft.NET.Sdk.Web

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IExchangeRates, FixedRates>();   // dependency injection
var app = builder.Build();

app.MapGet("/convert/{amount:decimal}/{from}/{to}",
    (decimal amount, string from, string to, IExchangeRates rates) =>
        rates.TryConvert(amount, from, to, out decimal result)
            ? Results.Ok(new { amount, from, to, result })
            : Results.NotFound($"No rate from {from} to {to}"));

app.Run();

Read it with what you know: builder.Services is the dependency-injection container, and asking for an IExchangeRates parameter makes the framework pass in the registered implementation, exactly the interface-based design from the generics lesson. The lambda is an endpoint; its parameters are bound from the route, and the anonymous object it returns is serialised to JSON. Configuration (from appsettings.json, environment variables and secrets), structured logging and health checks are all built in.

Around it:

  • Entity Framework Core maps classes to database tables and translates LINQ into SQL, as the LINQ lesson described. Lighter alternatives such as Dapper run hand-written SQL and map the rows to objects.
  • Blazor builds interactive web user interfaces in C# instead of JavaScript, running on the server or in the browser through WebAssembly.
  • Aspire (formerly .NET Aspire) describes a distributed application (services, databases, caches) in C# code and runs it all locally with a dashboard of logs and traces.
  • .NET MAUI and community frameworks such as Avalonia build desktop and mobile apps; WPF and Windows Forms remain in wide use for Windows desktop software.
  • Unity and Godot use C# for game logic, with their own runtimes and APIs.
ExplanationH

Testing with xUnit

.NET has three widely used test frameworks, xUnit, NUnit and MSTest, all run by the same dotnet test command and all supported by the editors. xUnit is a common choice for new projects, and its style is a good model. A test project is an ordinary project that references the code under test and the framework:

bash
dotnet new xunit -o TripSplitter.Tests
dotnet add TripSplitter.Tests reference TripSplitter
dotnet test

(The SDK's template references xUnit v2; xUnit v3, a newer major version, is published as separate packages with their own templates. The test code looks the same.) A test is a public method marked [Fact]; a parameterised test is a [Theory] with one [InlineData] attribute per case, and each case is reported as a separate test:

csharp
public class LedgerTests
{
    [Fact]
    public void Three_way_split_gives_the_extra_cent_to_the_first_sharer()
    {
        Assert.Equal(new[] { 33.34m, 33.33m, 33.33m }, Ledger.Shares(100m, 3));
    }

    [Theory]
    [InlineData(1, 2)]
    [InlineData(3334, 3)]
    [InlineData(99999, 7)]
    public void Shares_always_add_up_to_the_amount(long cents, int people)
    {
        decimal amount = cents / 100m;   // attributes cannot hold decimal constants
        Assert.Equal(amount, Ledger.Shares(amount, people).Sum());
    }

    [Fact]
    public void Sharing_with_nobody_is_an_error()
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => Ledger.Shares(10m, 0));
    }
}

Good tests share a shape, often called arrange, act, assert: set up the inputs, call the code, check the result. They are fast, independent of each other and of the clock, network and disk (which is where interfaces and fakes come in), and named so that a failure explains itself. Teams add integration tests that run the real web application in memory (ASP.NET Core's WebApplicationFactory) or against a real database in a container (the Testcontainers library), and use code coverage (coverlet, included in the template) as a guide to untested code, not as a target.

ExplanationH

Formatting, analyzers and CI

Consistency matters more than any particular style, so .NET teams automate it:

  • .editorconfig at the repository root records the team's style choices (indentation, var usage, brace placement, naming rules) and the severity of each analyzer rule. Editors and the compiler both read it.
  • dotnet format rewrites code to follow those rules; run with --verify-no-changes in CI, it fails the build if someone forgot.
  • Analyzers ship with the SDK and run inside the compiler: hundreds of rules about correctness, performance, security and style. Raise their level with the AnalysisLevel property, and add more from NuGet when a library ships its own.
  • Warnings as errors. Setting TreatWarningsAsErrors to true in the project file (often only in CI builds) keeps the warning count at zero, which is the only number at which people still read warnings.
  • Continuous integration runs dotnet restore, dotnet build, dotnet test and dotnet format --verify-no-changes on every pull request, typically in GitHub Actions or Azure Pipelines with an official setup-dotnet step that installs the SDK version pinned in global.json.

A common project file for a library on a well-run team looks like this:

xml
<PropertyGroup>
  <TargetFramework>net10.0</TargetFramework>
  <Nullable>enable</Nullable>
  <ImplicitUsings>enable</ImplicitUsings>
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  <AnalysisLevel>latest-recommended</AnalysisLevel>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
ComputationC

Project: a trip expense splitter

Four friends share a trip. Each logs what they paid and who it was for, in plain text. The program must read the log (reporting lines it cannot understand, not crashing on them), compute each person's balance, and propose a short list of transfers that settles everyone up. Money must be exact to the cent, and every cent must be accounted for.

csharp
// Trip splitter: who paid what, who owes whom, and the fewest transfers to settle up.
const string log = """
    Amina paid 160.00 for dinner; shared by Amina, Bruno, Chidi, Daria
    Bruno paid 45.50 for fuel; shared by Bruno, Chidi
    Chidi paid 300 for the cabin; shared by Amina, Bruno, Chidi, Daria
    Daria paid ten for snacks; shared by Daria
    Daria paid 10.00 for coffee; shared by Amina, Daria, Daria
    Bruno paid 33.34 for tickets; shared by Amina, Bruno, Chidi
    """;

var (expenses, problems) = ExpenseParser.ParseAll(log);
foreach (string problem in problems) Console.WriteLine($"skipped: {problem}");

Dictionary<string, decimal> balances = Ledger.Balances(expenses);
Console.WriteLine();
Console.WriteLine("Balances (positive = is owed money):");
foreach (var (person, balance) in balances.OrderByDescending(b => b.Value))
{
    Console.WriteLine($"  {person,-6} {balance,8:+0.00;-0.00;0.00}");
}

Console.WriteLine();
Console.WriteLine("To settle up:");
foreach (Transfer t in Ledger.Settle(balances))
{
    Console.WriteLine($"  {t.From} pays {t.To} {t.Amount:F2}");
}

public sealed record Expense(string PaidBy, decimal Amount, string Description, IReadOnlyList<string> SharedBy);

public readonly record struct Transfer(string From, string To, decimal Amount);

public static class ExpenseParser
{
    // "Name paid 12.34 for thing; shared by A, B, C"
    public static Expense Parse(string line)
    {
        string[] halves = line.Split("; shared by ", StringSplitOptions.TrimEntries);
        if (halves.Length != 2) throw new FormatException("expected '...; shared by ...'");

        string[] words = halves[0].Split(' ', 5, StringSplitOptions.RemoveEmptyEntries);
        if (words is not [var payer, "paid", var amountText, "for", var description])
            throw new FormatException("expected 'NAME paid AMOUNT for DESCRIPTION'");

        if (!decimal.TryParse(amountText, System.Globalization.CultureInfo.InvariantCulture, out decimal amount) || amount <= 0)
            throw new FormatException($"'{amountText}' is not a positive amount");

        string[] sharers = halves[1].Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
            .Distinct().ToArray();
        return new Expense(payer, amount, description, sharers);
    }

    public static (List<Expense> Expenses, List<string> Problems) ParseAll(string text)
    {
        List<Expense> expenses = [];
        List<string> problems = [];
        foreach (string line in text.Split('\n', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
        {
            try
            {
                expenses.Add(Parse(line));
            }
            catch (FormatException e)
            {
                problems.Add($"{e.Message} in \"{line}\"");
            }
        }
        return (expenses, problems);
    }
}

public static class Ledger
{
    // Split an amount into equal shares to the cent; leftover cents go to the first sharers.
    public static decimal[] Shares(decimal amount, int people)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(people);
        long cents = (long)Math.Round(amount * 100, MidpointRounding.AwayFromZero);
        long each = cents / people, extra = cents % people;
        return [.. Enumerable.Range(0, people).Select(i => (each + (i < extra ? 1 : 0)) / 100m)];
    }

    public static Dictionary<string, decimal> Balances(IEnumerable<Expense> expenses)
    {
        Dictionary<string, decimal> balance = [];
        foreach (Expense e in expenses)
        {
            balance[e.PaidBy] = balance.GetValueOrDefault(e.PaidBy) + e.Amount;
            decimal[] shares = Shares(e.Amount, e.SharedBy.Count);
            foreach (var (person, share) in e.SharedBy.Zip(shares))
            {
                balance[person] = balance.GetValueOrDefault(person) - share;
            }
        }
        return balance;
    }

    // Greedy settlement: the largest debtor pays the largest creditor, repeatedly.
    public static List<Transfer> Settle(IReadOnlyDictionary<string, decimal> balances)
    {
        if (balances.Values.Sum() != 0) throw new InvalidOperationException("balances do not sum to zero");

        var creditors = new PriorityQueue<string, decimal>();
        var debtors = new PriorityQueue<string, decimal>();
        var remaining = new Dictionary<string, decimal>(balances);
        foreach (var (person, b) in balances)
        {
            if (b > 0) creditors.Enqueue(person, -b);    // largest first
            else if (b < 0) debtors.Enqueue(person, b);  // most negative first
        }

        List<Transfer> transfers = [];
        while (debtors.TryDequeue(out string? debtor, out _) && creditors.TryDequeue(out string? creditor, out _))
        {
            decimal amount = Math.Min(-remaining[debtor], remaining[creditor]);
            transfers.Add(new Transfer(debtor, creditor, amount));
            remaining[debtor] += amount;
            remaining[creditor] -= amount;
            if (remaining[debtor] < 0) debtors.Enqueue(debtor, remaining[debtor]);
            if (remaining[creditor] > 0) creditors.Enqueue(creditor, -remaining[creditor]);
        }
        return transfers;
    }
}

It prints:

text
skipped: 'ten' is not a positive amount in "Daria paid ten for snacks; shared by Daria"

Balances (positive = is owed money):
  Chidi   +151.14
  Amina    +28.88
  Bruno    -70.02
  Daria   -110.00

To settle up:
  Daria pays Chidi 110.00
  Bruno pays Chidi 41.14
  Bruno pays Amina 28.88

How the design uses this course:

  • Records for data. Expense is an immutable record; Transfer is a readonly record struct, a small value. IReadOnlyList<string> says that nobody should modify an expense's sharers.
  • Parsing with patterns and the right failure mode. Parse uses a list pattern to check the sentence structure in one line and throws FormatException with a specific message for each problem. ParseAll turns each failure into a reported problem, so one bad line ("ten" is not a number) does not stop the rest. The culture is fixed to invariant, so "33.34" parses the same on a computer set to French.
  • decimal and cents. Shares converts to whole cents, divides with integer arithmetic, and gives the leftover cents to the first sharers, so the shares always add up exactly: 33.34 split three ways is 11.12, 11.11 and 11.11. Distinct quietly removes a repeated name in the coffee line; a stricter program might report it instead.
  • LINQ where it reads well, loops where they read better. Balances are accumulated in a dictionary in a plain loop; the shares are paired with sharers by Zip.
  • An invariant, checked. Balances must sum to zero, or money has been created or lost. Settle checks it and throws InvalidOperationException if not, a bug-detecting assertion, not a user error.
  • A classic algorithm. Settling uses two priority queues: repeatedly, the person who owes most pays the person owed most, as much as possible. This produces at most one fewer transfer than the number of people with a non-zero balance. (Finding the minimum number of transfers in general is a much harder problem, related to subset sum; the greedy answer is what most real apps use.)
  • Format strings. +0.00;-0.00;0.00 has three sections, for positive, negative and zero values, which is how the balances get their explicit signs.

Its tests

In a real repository, Ledger and ExpenseParser would live in a class library with an xUnit project beside it, using the tests shown in the testing section. Without a framework, the same ideas fit in a few lines. This program re-declares Shares and checks both specific examples and properties, rules that must hold for every input tried:

csharp
// A tiny test harness, to show the shape of unit tests without a test framework.
int passed = 0, failed = 0;

void Check(string name, bool condition)
{
    if (condition) passed++;
    else { failed++; Console.WriteLine($"FAIL: {name}"); }
}

void Throws<TException>(string name, Action action) where TException : Exception
{
    try { action(); Check(name, false); }
    catch (TException) { Check(name, true); }
}

// Example-based tests: one input, one expected output.
Check("three-way split of 100", Shares(100m, 3) is [33.34m, 33.33m, 33.33m]);
Check("one person pays everything", Shares(12.5m, 1) is [12.5m]);
Check("a single cent", Shares(0.01m, 2) is [0.01m, 0m]);
Throws<ArgumentOutOfRangeException>("nobody to share with", () => Shares(10m, 0));

// Property-based thinking: rules that must hold for every input we try.
foreach (decimal amount in new[] { 0.01m, 1m, 33.34m, 100m, 999.99m })
{
    for (int people = 1; people <= 7; people++)
    {
        decimal[] shares = Shares(amount, people);
        Check($"{amount}/{people}: sums to amount", shares.Sum() == amount);
        Check($"{amount}/{people}: fair to the cent", shares.Max() - shares.Min() <= 0.01m);
        Check($"{amount}/{people}: one share each", shares.Length == people);
    }
}

Console.WriteLine($"{passed} passed, {failed} failed");
return failed == 0 ? 0 : 1;

static decimal[] Shares(decimal amount, int people)
{
    ArgumentOutOfRangeException.ThrowIfNegativeOrZero(people);
    long cents = (long)Math.Round(amount * 100, MidpointRounding.AwayFromZero);
    long each = cents / people, extra = cents % people;
    return [.. Enumerable.Range(0, people).Select(i => (each + (i < extra ? 1 : 0)) / 100m)];
}

It prints:

text
109 passed, 0 failed

A top-level return sets the process's exit code, so a failing check would make the program exit with status 1, exactly how CI systems notice failing tests. Notice that is [33.34m, 33.33m, 33.33m] compares a whole array with a list pattern.

Extending it

Good next steps, each using a different part of the course: read the log from a file with File.ReadAllLinesAsync; support several currencies with a Money record and an IExchangeRates interface; report a repeated name as a problem; turn the program into a web API with the minimal API shown above; and move the tests into a real xUnit project.

Optional Christian reflection · Keeping accounts

A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.

Splitting costs fairly is a small, honest piece of work: every cent accounted for, nobody quietly paying more than their share. Scripture has a good deal to say about honest measures, and also about something beyond fairness: the early church in Jerusalem, Luke writes, "had all things common" (Acts 2:44, King James Version), and Paul urges that "now at this time your abundance may be a supply for their want" (2 Corinthians 8:14). A program can compute what is fair; it cannot decide when a friend should simply be told "this one is on me". That remains a human choice, and often a good one.

Further reading

Where to go next

You now know the language and its main tools. From here, depth comes from building things and reading good code:

  • Build something real with ASP.NET Core and EF Core, following the official tutorials on Microsoft Learn, or a small tool you will actually use, published as a file-based app or with Native AOT.
  • Read the source. The .NET runtime and libraries, ASP.NET Core and the C# compiler are all on GitHub. The collections, LINQ operators and System.Text.Json are excellent examples of careful C#.
  • Follow the language. New features are designed in the open in the dotnet/csharplang repository; each November's release notes and "What's new in C#" page summarise them. C# 15, released with .NET 11 in November 2026, adds union types and closed hierarchies, which make the record-and-pattern style of this course safer still.
  • Learn the neighbours. F#, also on .NET, shows where many of C#'s functional features came from; TypeScript, also designed by Anders Hejlsberg, will feel familiar; and Rust will sharpen your understanding of the memory questions from the previous lesson.
Exercises

Exercises

1. The ecosystem and a complete project

Warm-upComputational

Using the project's Shares method, what does this line print?

Console.WriteLine(string.Join(" ", Shares(1m, 3)));

2. The ecosystem and a complete project

CoreComputational

What does this line print?

Console.WriteLine($"{-0.5m:+0.00;-0.00;0.00} {0m:+0.00;-0.00;0.00} {7m:+0.00;-0.00;0.00}");

3. The ecosystem and a complete project

CoreComputational

The project's Ledger.Settle is given these balances: Ana +50, Ben -20, Caro -30. How many transfers does it return?

4. The ecosystem and a complete project

Warm-upHuman

An xUnit test class contains two methods marked [Fact] and one method marked [Theory] with four [InlineData(...)] attributes. How many test cases does dotnet test report?

5. The ecosystem and a complete project

CoreHuman

Your team wants every pull request to fail if the code is not formatted according to the team's rules. Which combination does that?

Choose one

6. The ecosystem and a complete project

CoreHuman

Which practices are sound when managing NuGet dependencies? (Choose all that apply.)

Choose all that apply

Further reading and resources