Preserve or select union storage
Advanced · C#. Raw storage preserves bytes whose interpretation may be unknown. Explicit member selection is useful when creating a new value.
Run this example
Prerequisites: the repository's .NET 10 SDK and a checkout of this source. Run from the repository root:
dotnet run --project docs/examples/CStructSharp.Docs.Examples.csproj -c Release -- preserve-union
The runner checks raw 34 12 round trip; selected small writes A5 00. Success includes PASS preserve-union.
Try the related browser lesson.
Complete program
The layout, options, input bytes, helper methods, and required types are all included. To adapt it outside the repository, create a .NET 10 console project, add CStructSharp, and replace Program.cs with this complete file. These examples follow the source version; use a matching package when testing a release.
Download the complete C# source.
// Generated from executable documentation examples. Edit the source region, then regenerate.
using System;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Buffers;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CStructSharp;
using CStructSharp.Codecs;
using CStructSharp.Diagnostics;
using CStructSharp.Introspection;
using CStructSharp.Values;
internal static partial class Program
{
public static void Main()
{
PreserveUnion();
Console.WriteLine("PASS preserve-union");
}
private static void PreserveUnion()
{
var layout = new CStruct("union choice { uint8 small; uint16 large; };");
UnionValue parsed = layout.ReadValue<UnionValue>(new byte[] { 0x34, 0x12 }, "choice");
Equal("choice", parsed.UnionName);
Equal((ushort)0x1234, (ushort)parsed.Members["large"]!);
SequenceEqual([0x34, 0x12], layout.Serialize("choice", parsed));
UnionValue selected = UnionValue.FromMember("choice", "small", (byte)0xA5);
SequenceEqual([0xA5, 0x00], layout.Serialize("choice", selected));
}
private static void Equal<T>(T expected, T actual)
{
if (!EqualityComparer<T>.Default.Equals(expected, actual))
{
throw new InvalidOperationException($"Expected '{expected}', received '{actual}'.");
}
}
private static void SequenceEqual(byte[] expected, byte[] actual)
{
if (!expected.AsSpan().SequenceEqual(actual))
{
throw new InvalidOperationException(
$"Expected {Convert.ToHexString(expected)}, received {Convert.ToHexString(actual)}.");
}
}
}
Try it and diagnose mistakes
Predict the result when selecting large with value 4660.
Answer: The little-endian bytes are 34 12. The program contains assertions for its original inputs. When changing an input intentionally, update the expected assertion too; an unchanged assertion is not evidence that the new value is wrong.
Continue with the related guide or choose another recipe.