tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Size of struct and size of class in .NET

11 Feb 2019 1 mins .NET, .NET Core

I was playing with structs and classes recently and found something I had no idea .NET does. Although it’s not something groundbreaking, I’ll share it with you anyway.

Can you guess the size of this structure?

struct S
{
    bool b1;
    int i1;
    bool b2;
}

Yes, it’s 12 bytes (on x86). The bool fields are padded (basically for alignment and interoperability with Win32 API P/Invoke). So, it’s 1B bool + 3B padding + 4B int + 1B bool + 3B padding. This is kind of expected, if you’ve been around .NET for a while.

But what happens when I change it to class?

class C
{
    bool b1;
    int i1;
    bool b2;
}

Surprisingly for me, it becomes 8 bytes. Because the class is a reference to some memory, it’s not expected you use it for marshaling data between different environments like managed .NET code and unmanaged native code, hence the runtime can reorder the fields to better use the memory. In this case it would do 4B int + 1B bool + 1B bool + 2B padding.

I know I can play with StructLayout and even use explicit layout with offsets, it’s just interesting to see the behavior for classes.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.