Table of Contents

Read a fixed header

Beginner · C#. A two-byte kind and four-byte length occupy six packed bytes. The typed read maps them to a C# class that implements ICStructMapped<T>.

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 -- decode-header

The runner checks kind 2, length 6; typed read succeeds and truncated read fails. Success includes PASS decode-header.

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()
    {
        DecodeHeader();
        Console.WriteLine("PASS decode-header");
    }

    private static void DecodeHeader()
    {
        var layout = new CStruct("struct header { uint16 kind; uint32 length; };");
        ReadOnlySpan<byte> bytes = [0x02, 0x00, 0x06, 0x00, 0x00, 0x00];
        StructValue header = layout.Parse(bytes, "header");
        Equal((ushort)2, header.Get<ushort>("kind"));
        Equal(6U, header.Get<uint>("length"));

        bool read = layout.TryReadValue<Header>(bytes, "header", out Header? typed);
        True(read && typed is { Kind: 2, Length: 6 }, "Typed header result differed.");
        True(!layout.TryReadValue<Header>(bytes[..1], "header", out _), "Truncated TryReadValue should fail.");
    }

    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 True(bool condition, string message)
    {
        if (!condition)
        {
            throw new InvalidOperationException(message);
        }
    }

    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 first byte to 03 and update the expected kind.

Answer: kind is 3; length stays 6. 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.