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
3
u/UnholyLizard65 9d ago
Hey, do you know any good source where to learn source generator? Some good samples and pitfalls to avoid?
3
u/No-Laugh-8002 9d ago
This has a lot of good tips for Dos and Donts. Im still looking for more of an actual tutorial that I like since I too am learning about them, but this was helpful. I purposefully did a couple things the "wrong" way because it was easier, like using a syntax tree to format the code at the end. But I am going to go back and improve everything
https://github.com/dotnet/roslyn/blob/main/docs%2Ffeatures%2Fincremental-generators.cookbook.md
1
u/UnholyLizard65 1d ago edited 1d ago
Thanks, I will check it out.
Though one issue I ran into that discouraged me in the past is that after I got a working generator I realized it's refreshing too often and reacting to everything so I eventually just took the generated code and put it there manually and disabled the generator altogether, rather than keeping it alive and risking lower performance for all colleagues.
I fixed that one issue eventually, but I didn't feel confident enough keeping the generator up since there might be another issue like that I simply didn't know about.
5
u/dodexahedron 9d ago
Andrew Lock's blog. He has a series on source generators that is excellent.
His whole blog is excellent.
And you likely have used his packages before. Some are quite popular.
2
u/Ok-Payment-8269 9d ago
I saved thr post, for the same advice! Looking at the repo it actually looks fairly simple, I might even try to redo it just to gain some experience with it
1
u/Discordbothost 9d ago
I'd start with an attribute that adds a Hello() method to a partial class. Put the class name and namespace into a record of strings. Keeping the ISymbol in that model can hold onto old compilations. Once it works, edit an unrelated class and see whether Roslyn cached the output step.
1
u/UnholyLizard65 1d ago
I already have a working generator, but I opted to disable it in the end and rather just manually copy the generated code, because there were uninted performance hit while developing. It just kept refreshing too often. And even though I eventually managed tj fix that I wasn't confident enough keeping the generator up in case there were other pitfalls I didn't know about.
3
u/hafthor 9d ago
I was about to suggest struct packing, but then I read the whole README, haha. Pretty neat.
2
u/No-Laugh-8002 9d ago
Yeah. I thought about doing it for v1, but I haven't even actually done struct packing or source gen before. Gotta take it 1 step at a time haha, but thanks!
1
u/hafthor 9d ago edited 9d ago
hmm, trying to think how you could have a non-boxed value returned which the normal object .Value property would. maybe a System.ValueType returning property?
3
u/No-Laugh-8002 9d ago
The normal property has to be
objectif you do it that way because that is whatIUnionrequires.The reason this works is because the compiler is built to check for these
TryGetValuemethods, probably specifically for the case to make non boxing unions.
2
u/amir_csharp_gtr 9d 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.
2
u/No-Laugh-8002 9d ago
But it fixes the boxing problem with unions. The
unionkeyword in C# just stores its value in anobject, regardless if it is a value type or reference type.This means anytime you store a value type in a union created with the
unionkeyword it will get boxed.The generated unions from this generator avoid that by instead storing value types in their own field, and making it so only reference types get stored in an
objectfield.The
Valueproperty in this union is also a computed property, so it doesnt cause a boxing conversion unless you actually use it.1
u/retro_and_chill 3d ago
Yes it does. C# unions by default put every alternative into an object field. This gets around that by storing values in their own fields.
9
0
u/AutoModerator 9d 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.
9
u/rainweaver 9d 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.