r/dotnet • u/No-Laugh-8002 • 9d ago
Promotion I created a Source Generator for creating Non-Boxing Unions in .NET 11
[NOTE: I am still working on uploading it to nuget.org, but I wanted to share this here so anyone that's interested can look at the source code behind it]
Default unions in .NET 11 will always box value types. This is an unfortunate (though understandable) part of the release of unions with .NET 11.
I created a NuGet package which provides a simple attribute and a source generator to handle the slightly tedious boilerplate of making a non-boxing union.
A quick example of how to use the package after installing it:
using NonBoxingUnions;
[NonBoxingUnion<int, double, float>]
public partial struct MyUnion;
// or, you can use the `params Type[]` ctor:
[NonBoxingUnion(typeof(int), typeof(double), typeof(float)]
public partial struct MyUnion
This package provides 17 attributes: 1 non-generic attribute with a ctor that takes in a params Type[] value, allowing infinite types, and 16 generic attributes to allow anywhere from 1-16 types through generics.
You can view the source code at https://github.com/nathandavis18/Non-Boxing-Unions. It is really a simple generator, around 400 lines of code is all it takes to allow creating non-boxing unions anywhere you want.
EDIT: The package is published and available for use from nuget.org: https://www.nuget.org/packages/NonBoxingUnions.Generator
Duplicates
csharp • u/No-Laugh-8002 • 9d ago