r/dotnet • u/No-Laugh-8002 • 3d 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 ;
public partial
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
9
u/rainweaver 2d ago
Looks great. This would have been fantastic for e.g. Unity - but no dice, as it’s stuck in a older .NET version for the time being.
3
u/UnholyLizard65 2d ago
Hey, do you know any good source where to learn source generator? Some good samples and pitfalls to avoid?
3
u/hafthor 2d ago
I was about to suggest struct packing, but then I read the whole README, haha. Pretty neat.
7
u/jetmarijuana 3d ago
Generic is the boss
1
u/amir_csharp_gtr 2d ago
What you are doing has nothing to do with boxing or unboxing. You change dynamic dispatch type checking which is slow to deterministic static dispatch try get value.
0
u/AutoModerator 3d ago
Thanks for your post No-Laugh-8002. Please note that we don't allow spam, and we ask that you follow the rules available in the sidebar. We have a lot of commonly asked questions so if this post gets removed, please do a search and see if it's already been asked.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.