Table of Contents

Write and update a header

Beginner · C#. Serialize creates bytes. Update changes the existing kind without shifting the length field.

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 -- header-round-trip

The runner checks 03 00 06 00 00 00 after updating kind. Success includes PASS header-round-trip.

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()
    {
        HeaderRoundTrip();
        Console.WriteLine("PASS header-round-trip");
    }

    private static void HeaderRoundTrip()
    {
        var layout = new CStruct("struct header { uint16 kind; uint32 length; };");
        byte[] bytes = layout.Serialize("header", new Dictionary<string, object?> { ["kind"] = 2, ["length"] = 6 });
        SequenceEqual([2, 0, 6, 0, 0, 0], bytes);
        using var stream = new MemoryStream(bytes);
        layout.Update(stream, "header.kind", 3);
        SequenceEqual([3, 0, 6, 0, 0, 0], stream.ToArray());
        Header header = layout.ReadValue<Header>(stream.ToArray().AsSpan(), "header");
        Equal((ushort)3, header.Kind);
        Equal(6U, header.Length);
        Console.WriteLine($"Updated kind = {header.Kind}; length = {header.Length}");
    }

    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)}.");
        }
    }

    public sealed class Header : ICStructMapped<Header>
    {
        public ushort Kind { get; set; }

        public uint Length { get; set; }

        public static Header ReadFrom(StructValue source)
        {
            return new Header { Kind = source.Get<ushort>("kind"), Length = source.Get<uint>("length") };
        }

        public static void WriteTo(Header value, StructValue target)
        {
            target["kind"] = value.Kind;
            target["length"] = value.Length;
        }

        [ModuleInitializer]
        internal static void Register()
        {
            MappedTypes.Register<Header>();
        }
    }

    #region api-guide-map-mapped-type
    // The generator writes ReadFrom, WriteTo, and the registration for this partial class.
    [CStructMapped]
    public sealed partial class MappedPoint
    {
        public short X { get; set; }

        public short Y { get; set; }
    }
    #endregion
}

Try it and diagnose mistakes

Change the replacement kind to 4.

Answer: The first byte becomes 04; the other five bytes stay the same. 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.