I lead a weekly book club and discussion group at work, and recently a teammate suggested we work through the interactive Brown University edition of "The Rust Programming Language".

It kicked off some of the best technical discussions we've had all year. Most of the conversation kept circling back to how much work Rust pushes onto the compiler. Explicit error handling, exhaustive pattern matching, data-owning locks, #[must_use], typestate transitions, and Clippy's pedantic lints catch whole categories of bugs before a single test runs.

The catch is that we're primarily a .NET shop. You don't wake up on a Monday and rewrite a decade of C# services in Rust, and most of the time you shouldn't want to. Still, I walked out of those meetings wanting more of that safety net in the .NET codebases we already own.

That rabbit hole became Ferrous: a modular suite of zero-allocation primitives, source generators, Roslyn analyzers, IDE quick-fixes, and a dotnet fe CLI for .NET 10 and .NET 11.

Deterministic Safety for the Agentic Coding Loop

A big part of the goal with Ferrous is giving the agentic coding loop deterministic, compile-time guardrails.

In my last post, Impossible Mission: Reviewing PRs in the Agentic Coding Era, I wrote about how the era of reading every line of every pull request is over. When an agent opens a PR that touches dozens of files and thousands of lines, line-by-line review turns into a rubber stamp. The hard question is how you trust code you didn't read line by line. I split that into coherence (keeping a shared mental model of the system) and confidence (knowing the code actually holds up).

Containerized integration tests are one half of confidence. The compiler is the other.

Most of the guardrails we put around coding agents right now are probabilistic. Prompts, AGENTS.md files, doc comments, and LLM-based PR reviews all help, and I use them, but they are still suggestions. When a context window fills up or a diff gets big, probabilistic rules get bent or missed.

An agent can easily write code that looks fine in a skim while swallowing a return value, holding a lock across an await, missing an enum case in a switch, swapping two primitive arguments, or reusing an object after a state transition. If those rules live in tribal knowledge, Markdown files, or PR comments, they will slip through. If they live in the type system and Roslyn analyzers, dotnet build fails every time with a rustc-style error and a help: hint. The agent sees the failure in its inner loop and fixes it on the next turn, before a human ever opens the PR.

That also takes weight off code review. If the build refuses to pass when an error is ignored, a lock is held across an await, or a workflow skips a state transition, reviewers don't have to hunt for those bugs in a 3,000-line diff. They can focus on system design and coherence instead.

A few years ago, building a suite of Roslyn control-flow analyzers and Clippy-style lints for C# would have felt like too much ceremony for the payoff. As I wrote in Rethinking Build vs. Rent, that tradeoff has shifted. Tight, deterministic compiler feedback is a big reason Rust works so well with coding agents, and Ferrous is my attempt to bring more of that to .NET.

What's Included

You can install everything via the metapackage (dotnet add package Ferrous) or pull individual packages a la carte.

1. Zero-Allocation Result<T, TError>, Option<T>, and ScopeGuard

Ferrous.Results provides allocation-free readonly struct implementations of Result<T, TError> and Option<T>, alongside validated primitives like NonZero<T>, NonEmptyString, NonEmptyList<T>, and CheckedMath. Ferrous.Guard adds ref struct scope guards (ScopeGuard.Defer(...)) for deterministic cleanup and commit/rollback flows without closure allocations:

using Ferrous.Guard;
using Ferrous.Results;

Result<int, string> ParsePort(string input) =>
    int.TryParse(input, out int port) && port is > 0 and <= 65535
        ? Result.Ok<int, string>(port)
        : Result.Err<int, string>($"Invalid port: {input}");

using var rollback = ScopeGuard.Defer(tx, static t => t.Rollback());
tx.Commit();
rollback.Dismiss();

2. Zero-Boxing [DiscriminatedUnion] and [Newtype] Source Generators

Ferrous.Unions uses an incremental source generator to emit zero-boxing discriminated unions (with exhaustive .Match(...) and JSON converters) and validated [Newtype] structs so primitive obsession doesn't leak across your domain boundaries:

using Ferrous;

[DiscriminatedUnion]
public readonly partial struct Shape
{
    public static partial Shape Circle(double radius);
    public static partial Shape Rect(double width, double height);
    public static partial Shape Point();
}

double area = Shape.Circle(3.0).Match(
    onCircle: r => Math.PI * r * r,
    onRect: (w, h) => w * h,
    onPoint: () => 0.0);

3. Ownership, Typestate Protocols, and [MustUse]

Ferrous.Annotations, Ferrous.Ownership, and Ferrous.States use Roslyn's control-flow graph to enforce [MustUse] return values (FE0001), track moved values across [ConsumesSelf] methods (FE0200), and prevent direct construction of non-initial typestates (FE0300):

using Ferrous;

[Typestate(IsInitial = true)]
public sealed class Draft
{
    public string Body { get; set; } = "";

    [ConsumesSelf]
    public Published Publish() => new Published();
}

[Typestate]
public sealed class Published { }

var draft = new Draft();
var published = draft.Publish(); // OK: consumes `draft`
_ = draft.Body;
// error FE0200: use of moved value 'draft': value moved into 'Publish()' at line 16;
//   help: reassign 'draft' before reusing it, or avoid consuming it

_ = new Published();
// error FE0300: cannot construct non-initial typestate 'Published' directly;
//   help: transition from an initial state via a [ConsumesSelf] method

Every FE* diagnostic is modeled on rustc's output: a short summary, the causal location wired into IDE AdditionalLocations, a help: hint, and a docs link, paired with Roslyn quick-fixes for the common rules. Those help: hints work just as well for an agent reading dotnet build output as they do for a developer in an IDE.

4. Data-Owning Concurrency and Thread-Safety Analyzers

In standard C#, a lock object sits next to the state it's supposed to protect, and nothing stops another method from touching the field without acquiring the lock. Ferrous.Concurrency brings Rust's data-owning Mutex<T>, AsyncMutex<T>, RwLock<T>, OnceLock<T>, LazyLock<T>, TypedChannel, and structured TaskScope to .NET. Ferrous.Concurrency.Analyzers backs them up at compile time, flagging [ThreadConfined] (!Send) escapes, mutable static state, locks held across await, and detached Task.Run calls inside a TaskScope.

5. Clippy-Style Pedantic Lints and Rust-Inspired Testing

Flipping <FerrousPedantic>true</FerrousPedantic> enables Clippy-style rules (FE0400–FE0428), including exhaustive switches, bounds-aware indexing, and immutable DTO checks. On the test side, Ferrous.Testing adds trybuild-style negative compilation assertions (CompileAssert), proptest-style property testing with shrinking (PropAssert.ForAll), and AllocAssert.Zero for hot-path verification.

There are also opt-in integration packages for the rest of the .NET stack: Ferrous.AspNetCore (NativeAOT-friendly Result/Option to ProblemDetails and OpenAPI), Ferrous.EntityFrameworkCore (ValueConverters for [Newtype]/NonEmptyString/NonZero<T>), and Ferrous.Http (exception-free HttpClient returning Result<T, HttpError>).

Polyfill Today, Light Up Tomorrow

I didn't want Ferrous to fight the direction of C# and .NET. The .NET team is already shipping several of these features in-box, so Ferrous polyfills what's missing on .NET 10 and switches to native support as it lands in .NET 11 and C# 15:

  • [DiscriminatedUnion] emits .NET 11's native [Union] attribute and TryGetValue pattern when targeting net11.0, so C# 15's exhaustive switch expressions work natively with zero boxing.
  • FE0400 recognizes C# 15's closed (IsClosedTypeAttribute) type hierarchies alongside [Closed].
  • net11.0 targets compile with runtime-async=on automatically.

As the language and BCL absorb more of these guarantees, Ferrous gets thinner instead of turning into legacy baggage.

The Music Store Case Study

To see how these pieces hold up together in a real web app (ASP.NET Core Minimal APIs, EF Core on SQLite, OpenAPI, validated newtypes, and typestate-enforced checkout workflows), I ported the classic .NET Music Store end to end.

You can read the 7-chapter walkthrough at ferrous.westness.cc/music-store/, browse the companion repository, or check out the live Music Store API docs.

The main documentation is at ferrous.westness.cc and the source is on GitHub at github.com/bradwestness/Ferrous. If you're a .NET shop eyeing Rust's compile-time guarantees, or looking for deterministic guardrails for your coding agents, give it a spin and let me know what you think.