CodeBlanks Logo Icon CodeBlanks

StructLayout

C# course · Expert · Lesson 15/47

Learn to control memory layout with StructLayout.

What is StructLayout?

The StructLayout attribute controls the memory layout of a struct or class. [StructLayout(LayoutKind.Sequential)] places fields in declaration order; this matches C-style structs and is the most common option.

With LayoutKind.Explicit and [FieldOffset(...)] you can place each field by hand. This is critical when calling native APIs that expect a C-style struct memory layout.

Explicit and FieldOffset

With LayoutKind.Explicit each field gets a position such as [FieldOffset(0)]. This lets a field share memory with fields of different types, producing a union.

For example a 4-byte int and a 4-byte float can share the same offset. This technique brings C union behavior to C# and is useful in low-level data structures.

Exercise Define a Point struct

Define [StructLayout(LayoutKind.Sequential)] struct Point { public int X; public int Y; }. In Main write Point p; p.X = 3; p.Y = 4; and print the sum with Console.WriteLine(p.X + p.Y);.

Show example solution
Point p; p.X = 3; p.Y = 4; Console.WriteLine(p.X + p.Y);
Example solution:
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
struct Point
{
    public int X;
    public int Y;
}

class Program
{
    static void Main()
    {
        Point p;
        p.X = 3;
        p.Y = 4;
        Console.WriteLine(p.X + p.Y);
    }
}

Test yourself

  1. Which LayoutKind orders fields by declaration?

    • Auto
    • Explicit
    • Random
    • Sequential
    Show answer

    Sequential — Correct. Sequential places fields in declaration order.

  2. Complete the StructLayout attribute

    [____(LayoutKind.Sequential)] struct Point { public int X; public int Y; }
    Show answer
    [StructLayout(LayoutKind.Sequential)] struct Point { public int X; public int Y; }
  3. Match the LayoutKind types

    LayoutKind.Sequential
    Declaration order
    LayoutKind.Explicit
    Manual offset
    FieldOffset(0)
    Offset 0
    StructLayout
    Layout attribute

All lessons in Expert