CloudMesh.Variant
2.0.108
dotnet add package CloudMesh.Variant --version 2.0.108
NuGet\Install-Package CloudMesh.Variant -Version 2.0.108
<PackageReference Include="CloudMesh.Variant" Version="2.0.108" />
<PackageVersion Include="CloudMesh.Variant" Version="2.0.108" />
<PackageReference Include="CloudMesh.Variant" />
paket add CloudMesh.Variant --version 2.0.108
#r "nuget: CloudMesh.Variant, 2.0.108"
#:package CloudMesh.Variant@2.0.108
#addin nuget:?package=CloudMesh.Variant&version=2.0.108
#tool nuget:?package=CloudMesh.Variant&version=2.0.108
CloudMesh.Variant
A boxing-free discriminated union for .NET — carry any primitive, Guid, DateTime, enum, small struct,
null, or reference in one fixed-size Value, and read it back out with zero heap allocations.
When you gather heterogeneous values into an object?[], every value type gets boxed — a heap allocation per
element. In hot paths (parsing JSON, staging rows for a bulk loader, buffering columnar data) that is millions of
allocations and constant GC pressure, purely to shuttle ints and bools around. Value stores those inline in
an overlapped struct field instead, so nothing boxes.
- Targets: .NET 8, 9, 10, 11 — License: MIT
- A
Valueis areadonly structof 24 bytes on 64-bit (an 8-byte object reference plus a 16-byte inline union); aValue[]is a flat array with no per-element heap objects. As<T>()/TryGetValue<T>()round-trips honourNullable<T>— a storedintreads back asint?, a storednullreads back as any nullable/reference type.- On .NET 11,
Valueis a union type — assign andswitchover it like a declaredunion, without the boxing a declaredunionwould cost. See Union support.
Install
dotnet add package CloudMesh.Variant
The problem it solves
object?[] values = new object?[3];
values[0] = 4; // int → boxed (heap allocation)
values[1] = null; // null → no boxing
values[2] = true; // bool → boxed (heap allocation)
Two allocations, just to hold two value types. With Value:
using CloudMesh.Variant;
Value[] values = new Value[3];
values[0] = 4; // int → no boxing (implicit conversion)
values[1] = null; // null → no boxing
values[2] = true; // bool → no boxing
Zero allocations. The array is a contiguous block of 16-byte structs.
Reading values back
Use As<T>() (throws on mismatch) or TryGetValue<T>() (returns false):
Value v = 42;
int i = v.As<int>(); // 42
int? n = v.As<int?>(); // 42 — Nullable<T> round-trips
bool ok = v.TryGetValue<int>(out i); // true
bool no = v.TryGetValue<long>(out _); // false — no implicit widening; the stored type must match
// Explicit conversion operators exist for the built-in types too:
var back = (int)v; // 42
Nulls and reference types behave as you'd expect:
Value empty = null;
empty.IsNull; // true
empty.TryGetValue<string>(out var s); // true, s == null
empty.TryGetValue<int?>(out var maybe); // true, maybe == null
empty.TryGetValue<int>(out _); // false — a plain int can't be null
Inspect what's inside with Type:
Value g = Guid.NewGuid();
g.Type; // typeof(System.Guid) — reports the real type, not the internal storage type
What stores without boxing
| Category | Examples |
|---|---|
| Primitives | bool, byte, sbyte, char, short/ushort, int/uint, long/ulong, float, double |
| Nullable primitives | int?, bool?, double?, decimal?, Guid?, … (all of the above) — the has-value flag is the null-ness of the reference field, so only the underlying value is stored |
| Date/time | DateTime, DateTimeOffset (UTC and common quarter-hour offsets are packed inline) |
| Identifiers & enums | Guid, any enum |
| Buffers | ArraySegment<byte>, ArraySegment<char> |
| Small unmanaged structs | any struct with no references that fits in the inline union |
| Anything else | reference types & large/managed structs — held as a plain object reference (no extra allocation) |
Values whose type is only known generically go through Value.Create<T>(value), which picks the inline
representation automatically:
static Value Wrap<T>(T item) => Value.Create(item); // no boxing for the inline-eligible types above
Union support (.NET 11)
On .NET 11 and later, Value implements the C# 15 union contract, so the compiler treats it as a union type:
implicit conversions from each case type, pattern matching that unwraps to the stored value, and exhaustiveness
checking on switch expressions.
Value value = 42;
var description = value switch
{
int i => $"int: {i}",
double d => $"double: {d}",
Guid g => $"guid: {g}",
string s => $"string: {s}",
null => "no value",
object o => $"other: {o}",
};
The difference from a compiler-declared union is the allocation profile. A declared union stores its
contents as a single object?, so every value-type case boxes — on creation and on every match. Value
implements the union contract's non-boxing access pattern instead: it declares a TryGetValue overload per
case type and a HasValue property, so the compiler lowers value is int i to a TryGetValue(out int) call
and value is null to a HasValue check. Neither touches the boxing Value accessor:
// 1,000,000 iterations of the switch above over an inline int: 0 bytes allocated.
Each scalar factory takes the nullable form — int?, bool?, DateTime?, … — because a Value can
always be null, and Value(T?) is the constructor that models that. Under the C# 15 rules a nullable factory
parameter makes the underlying type the case type, paired with a TryGetValue whose out parameter is that
underlying type. A single factory per scalar therefore accepts both int and int? sources, while
v is int i binds to TryGetValue(out int) and never boxes:
int? maybe = 42;
Value value = maybe;
value is int; // true — matched via TryGetValue(out int), stored inline, no box
value is null; // false
Value none = (int?)null;
none is int; // false
none is null; // true — matched via HasValue
The full case-type list is bool, byte, sbyte, char, short, ushort, int, uint, long,
ulong, float, double, decimal, Guid, DateTime, DateTimeOffset (each created from its nullable
form), ArraySegment<byte>, ArraySegment<char>, string and object. The two ArraySegment factories stay
non-nullable — an absent segment is simply a null Value. object keeps the union sound, since a Value can
hold any reference.
Notes:
- Patterns apply to the union's contents, not to the
Valuestruct:value is Valuedoes not match, andvalue is inttests the stored value. This changes the meaning of patterns that compiled before C# 15:value is Valuewas always true and is now false, andvalue is objectis now false for a nullValue. - A project targeting net11.0 with
LangVersionpinned below 15 gets error CS9327 ("Feature 'unions' is not available") on any type pattern over aValue, such asvalue is object. The non-pattern API is unaffected. The default language version for net11.0 is C# 15, so only projects that pin an older version are affected. - The existing conversion operators take priority over the union conversion, so
Value v = 42still stores inline exactly as it does on .NET 8–10. Everything in this section is additive; no existing API changed. ((IUnion)value).Valueis the standard union accessor. It boxes inline value types, by definition — useTryGetValue<T>/As<T>when you want the value without a box.
There is a runnable demo under samples/VariantSample.
Use cases
- Columnar / bulk-load staging — parse a record's fields into a
Value[], reorder to match the loader's column order, and emit, all without boxing a single scalar. - Generic buffers & message payloads — pass arbitrary scalar payloads through a generic pipeline without an
objectbox per message. (CloudMesh.DataBlocks usesValueinternally for exactly this.) - Interpreters / dynamic values — a compact cell type for a stack or register file that mixes numeric, boolean, and reference values.
Gotchas
- Exact-type match on read.
TryGetValue<T>does not widen or convert — a storedintis not readable aslongordouble. Read it as the type you stored (optionally itsNullable<T>), then convert yourself. As<T>()throwsInvalidCastExceptionon a mismatch; useTryGetValue<T>when a miss is expected.decimalis stored inline — it is a 16-byte unmanaged value that fits the inline union (exactly likeGuid), so storing adecimaldoes not box. Nor doesdecimal?: aValuerecords "no value" as a null object reference, so theNullable<T>has-value flag is never stored and only the 16-byte payload has to fit. The same goes forGuid?and every other nullable primitive.ArraySegmentvs array. A segment stores the backing array plus offset/count inline; reading it back as the bare array type is intentionally rejected so a segment can't silently masquerade as the whole array.
MIT © Jessie Wadman. Part of CloudMesh.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- No dependencies.
-
net11.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (2)
Showing the top 2 NuGet packages that depend on CloudMesh.Variant:
| Package | Downloads |
|---|---|
|
CloudMesh.DataBlocks
Lightweight building blocks for creating complex message processing pipelines |
|
|
Primodel.Sdk
Contracts for authoring Primodel plugins. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 2.0.108 | 0 | 11/21/2026 |
| 2.0.107 | 832 | 11/14/2026 |
| 2.0.105 | 765 | 11/12/2026 |
| 2.0.104 | 366 | 11/9/2026 |
| 2.0.103 | 2,664 | 9/25/2026 |
| 2.0.101 | 181 | 8/29/2026 |
| 2.0.100 | 3,449 | 8/3/2026 |
| 2.0.99 | 151 | 7/14/2026 |
| 2.0.98 | 156 | 7/14/2026 |
| 2.0.97 | 599 | 7/14/2026 |
| 2.0.96 | 145 | 6/28/2026 |
| 2.0.95 | 143 | 6/28/2026 |
| 2.0.94 | 145 | 6/28/2026 |
| 2.0.93 | 180 | 6/27/2026 |
| 2.0.92 | 149 | 6/23/2026 |
| 2.0.89 | 341 | 12/18/2025 |
| 2.0.87-preview | 237 | 8/11/2025 |
| 2.0.85-preview | 162 | 1/29/2025 |
| 2.0.76-preview | 172 | 1/15/2025 |
| 2.0.75-preview | 171 | 1/15/2025 |