Skip to content

Instantly share code, notes, and snippets.

@Houtamelo
Houtamelo / README.md
Created November 16, 2026 23:57
Spire C#: exhaustive matching and discriminated unions for Unity

I love discriminated unions and how they allow one to associate data with specific enum variants. I'm not the only one, other developers have tried bringing them to C# by using Roslyn's Source Generators, example: OneOf.

I tried using several of those implementations, however, as someone who got introduced to discriminated unions through Rust, it was clear to me that the existing Source Generators weren't enough:

  • Most of them implement exhaustive matching via a Match(Func<VariantA>, Func<VariantB>) method, which results in closures(heap allocation) every time you had to use such feature; we Unity developers are definitely not fans of heap allocation. Closures also mean the C# compiler loses some context in the process.
  • Most also use classes/records (more heap allocation!) for the union types themselves.

So I set out in an attempt to make the best implementation I could, trying to keep them ergonomic without sacrificing performance or memory usage. After several

@Houtamelo
Houtamelo / lesson_deref.md
Last active April 16, 2025 23:52
Lesson - Deref

Introduction

This lesson aims to teach the reader about the inner-workings of Rust's *(deref operator) and trait Deref, as well as how to take advantage of those features.

Requirements

This lesson assumes that:

  • You have amateurish understanding of Rust's type system. Most importantly, understand that references are types, meaning &T, &mut T and T are all different types.

Terminology