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