Read an item in a nested array
Intermediate · C#. Array indexes start at zero. Each item occupies two bytes, so the second starts at offset 2.
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 -- nested-array
The runner checks packet.items[1].id is 2; exact four-byte round trip. Success includes PASS nested-array.
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()
{
NestedArray();
Console.WriteLine("PASS nested-array");
}
private static void NestedArray()
{
var layout = new CStruct("struct item { uint16 id; }; struct packet { item items[2]; };");
byte[] bytes = [1, 0, 2, 0];
Equal((ushort)2, (ushort)layout.ReadValue(bytes.AsSpan(), "packet.items[1].id")!);
object packet = layout.Parse(bytes.AsSpan(), "packet");
SequenceEqual(bytes, layout.Serialize("packet", packet));
}
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
Select items[0].id instead.
Answer: The first id is 1. 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.