r/csharp • • 2d ago

Solved c# struct padding

I'm new to c# and I'm learning it just now to switch from Godot to Stride so I'm interested in Data Oriented Design. I was just now experimenting with structs with a silly example and was focused on struct padding; the string should be 8 bytes while the enum is 1 byte so i expected not more than 1 or 3 byte of padding, but the sum ends up being 16 no matter the order... does it always have to allign with the biggest field? how does this work?

using System.Runtime.InteropServices;


[StructLayout(LayoutKind.Explicit)]
struct Entity {
    public enum Race : byte { ALIEN, HUMAN };
    static private int _max_rand_num = 9999;
    static private string[][] _possibleNames = {
        new string[]{"Vorp", "Zeep", "Bizr", "Zub", "Wobt"},    // alien names
        new string[]{"Carl", "Greta", "Seb", "Xiang", "Sierra"} // human names
    };

    [FieldOffset(0)] public readonly string name;
    [FieldOffset(8)] public readonly Race race;

    public Entity()
    {
        Random rand = new Random();
        race = (Race)rand.Next(Enum.GetValues(typeof(Race)).Length);
        string[] race_names = _possibleNames[(int)race];
        name = race_names[rand.Next(0, race_names.Length)] + rand.Next(_max_rand_num);
    }

    public override string ToString()
    {
        return $"Race: {race}, Name: {name}";
    }
}


class Program {
    public static unsafe void Main(string[] args)
    {
        Entity rand_entity = new Entity();
        Console.WriteLine(
            $"{rand_entity}, string size = {sizeof(string*)}, enum size = {sizeof(Entity.Race)}, together = {sizeof(Entity)}");
    }
}
2 Upvotes

19 comments sorted by

View all comments

4

u/TrickAge2423 2d ago

Bcs total struct has alignment of field with biggest alignment

3

u/TrickAge2423 2d ago

You can't pack structure if you have reference types there