A simple NuGet package which fills the gap that the .NET 11 release did not cover: Non-Boxing Unions.
Currently, if you just declare a union as public union SomeUnion(int, double, float), the value will be boxed
into an object, which adds GC pressure and heap allocations that otherwise could have been avoided.
This package helps avoid all boxing conversions for value types with unions by creating bool TryGetValue(out T value) methods
for each type used by the union.
Under the hood, the C# compiler will utilize these methods when they exist, so instead of doing something like
if (union.Value is int i)
return i;It will instead call
if (union.TryGetValue(out int i))
return i;This package will generate 17 attributes:
- 1 attribute which allows up to
int.MaxValuetypes via aparams Type[]ctor. - 16 generic attributes, which will allow you to use anywhere from 1-16 generic type arguments
When declaring a non-boxing union, all you have to do is include the namespace, then apply the attribute to a partial struct (or alternatively fully qualify the attribute type):
using NonBoxingUnions;
[NonBoxingUnion(typeof(int), typeof(double), typeof(float), typeof(MyCustomStruct)]
partial struct MyUnion;
// or
[NonBoxingUnion<int, double, float, MyCustomStruct>]
partial struct MyOtherUnion;When using generics, apply them through the constructor syntax:
[NonBoxingUnion<int, double, float, MyCustomStruct>]
partial struct MyUnion<T>
{
public partial MyUnion(T value);
}Note that if you declare a non boxing union as an enclosed type, the enclosing type must also be partial. If the enclosing type is also an enclosed type, its enclosing type must be partial, etc. etc.
- Does not box value types: Utilizes the compiler calling
union.TryGetValue(out T value)to retrieve value types without boxing - Incremental Generation: Only re-generates the union when changes have been made
- No External Dependencies: The only dependency is that your consuming project targets .NET 11+
- Compiler Errors for malformed attributes: If your
[NonBoxingUnion]attribute is malformed a compiler error will be generated tagging the malformed union. - Discriminated Tag Backing Size Growth: If your union uses more than 255 types that require a discriminated field the backing size of the underlying tag structure grows with it, up to
int. - Unmanaged Value Type Packing When Non-Generic: If your union is not enclosed within a generic type and is not itself a generic type all packable value types will be packed by default.
- This means if you have an
int,short,ushort,byte,sbyte, andcharthe union will only be 8 bytes: 4 bytes for the int, 1 byte for abyte-sized tracking tag, and 3 bytes of padding. - This can be disabled by setting the
DisableStructPackingflag totrue.
- This means if you have an
- Supports Generic Types: You can define constructors using generic types. Doing so will automatically fill out the union with a field for the generic type, depending on its generic constraints:
- Unconstrained generic types and generic types constrained to
structorunmanagedget their own discriminated field to prevent boxing. - Generic types constrained to
classor wrapped in a reference type (such asList<T>) get assigned to the shared reference type field. - Constructors for the union must be
public partialand can only accept a single argument. Analyzer errors will be triggered for invalid constructors.- Invalid:
public MyUnion(T value) {},public partial MyUnion(T value, T2 value2);,public MyUnion() {} - Valid:
public partial MyUnion(T value);
- Invalid:
- While non-generic types can also be defined using the constructor syntax, you should prefer using the attribute's generic or
params Type[]syntax for defining known types. As such, an analyzer warning will be generated for constructors that define known types.
- Unconstrained generic types and generic types constrained to
- Non-Boxing Conversion between
Nullable<T>andT: Uses (and reuses) a delegate when attempting to extract the current value type.- If the
outtype is a reference type a boxing conversion still must happen. - If the
outtype isNullable<T>and the input type isTthe value is wrapped in a nullable and returned. - If the
outtype isTand the input type isNullable<T>the value is checked for null then assigned ifNullable<T>.HasValueistrue. - If the
outtype and the input type are both value types with no runtime relation (i.e.doubleandint) no conversion is made, and the delegate will immediately returnfalse.
- If the
See the Issues tab for a list of all known issues. I will be tracking any issues as well as feature requests from that tab.