Table of Contents

Patch a nested field in a stream

Intermediate · C#. The stream begins with a two-byte prefix. Set Position to the start of the selected structure before updating it.

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 -- patch-field

The runner checks EE EE 34 12 A5; invalid replacement preserves bytes and position. Success includes PASS patch-field.

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()
    {
        PatchField();
        Console.WriteLine("PASS patch-field");
    }

    private static void PatchField()
    {
        var layout = new CStruct("struct item { uint16 id; uint8 flags; }; struct root { item value; };");
        using var stream = new MemoryStream([0xEE, 0xEE, 0x34, 0x12, 0x01]);
        stream.Position = 2;
        layout.Update(stream, "root.value.flags", (byte)0xA5);
        SequenceEqual([0xEE, 0xEE, 0x34, 0x12, 0xA5], stream.ToArray());
        Equal(2L, stream.Position);

        byte[] before = stream.ToArray();
        Throws<CStructWriteException>(() => layout.Update(stream, "root.value.flags", 999));
        SequenceEqual(before, stream.ToArray());
        Equal(2L, stream.Position);
    }

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

    private static void Throws<TException>(Action action)
        where TException : Exception
    {
        try
        {
            action();
        }
        catch (TException)
        {
            return;
        }

        throw new InvalidOperationException($"Expected {typeof(TException).Name}.");
    }
}

Try it and diagnose mistakes

Try replacing flags with 999.

Answer: It does not fit uint8. Validation fails before changing the stream. 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.