Skip to content

About

A nuget package which allows creating non-boxing unions in C#, since the built in `union` keyword can't do that.

Resources

Stars

14 stars

Watchers

1 watching

Forks

Repository files navigation

NonBoxingUnions

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;

A Quick Example

This package will generate 17 attributes:

  • 1 attribute which allows up to int.MaxValue types via a params 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.


Full Feature Set

  • 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, and char the union will only be 8 bytes: 4 bytes for the int, 1 byte for a byte-sized tracking tag, and 3 bytes of padding.
    • This can be disabled by setting the DisableStructPacking flag to true.
  • 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 struct or unmanaged get their own discriminated field to prevent boxing.
    • Generic types constrained to class or wrapped in a reference type (such as List<T>) get assigned to the shared reference type field.
    • Constructors for the union must be public partial and 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);
    • 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.
  • Non-Boxing Conversion between Nullable<T> and T: Uses (and reuses) a delegate when attempting to extract the current value type.
    • If the out type is a reference type a boxing conversion still must happen.
    • If the out type is Nullable<T> and the input type is T the value is wrapped in a nullable and returned.
    • If the out type is T and the input type is Nullable<T> the value is checked for null then assigned if Nullable<T>.HasValue is true.
    • If the out type and the input type are both value types with no runtime relation (i.e. double and int) no conversion is made, and the delegate will immediately return false.

Known Issues

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.

About

A nuget package which allows creating non-boxing unions in C#, since the built in `union` keyword can't do that.

Resources

Stars

14 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages