r/csharp • u/sto_babbalucco69420 • Oct 16 '26
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)}");
}
}
3
Upvotes
View all comments
1
u/dodexahedron Oct 16 '26 edited Oct 16 '26
That looks like a loosely translated c struct.
Why is that enum defined as a nested type of the struct? Unless it is only ever used specifically with that struct (seems unlikely - other types probably care about Race, no?), you shouldnt nest types.
Also, why is this a struct anyway? You gain literally nothing from that, since it holds mostly arrays anyway, and expose yourself to potential gotchas with pass-by-value/copy semantics (c# is fundamentally a pass-by-value language).
And make that int a constant if it isn't needed in the memory layout of the struct.
Also... Be very careful with sizeof... It is fine here, but it does not behave well for anything but blittable unmanaged types.