Potty Little Details

Just another WordPress.com weblog

How the CLR Controls the Layout of a Type’s Fields

leave a comment »

To improve performance, the CLR is capable of arranging the fields of a type any way it
chooses. For example, the CLR might reorder fields in memory so that object references
are grouped together and data fields are properly aligned and packed. However, when
you define a type, you can tell the CLR whether it must keep the type’s fields in the
same order the developer specified them or whether it can reorder as it sees fit.
You tell the CLR what to do by applying the System.Runtime.-
InteropServices.StructLayoutAttribute attribute on the class or structure
you’re defining. To this attribute’s constructor, you can pass LayoutKind.Auto to have
the CLR arrange the fields or LayoutKind.Sequential to have the CLR preserve
your field layout. If you don’t explicitly specify the StructLayoutAttribute on a type
that you’re defining, your compiler selects whatever layout it thinks best.
You should be aware that Microsoft’s C# compiler selects LayoutKind.Auto for
reference types (classes) and LayoutKind.Sequential for value types (structures). It
is obvious that the C# compiler team feels that structures are commonly used when
interoperating with unmanaged code, and for this to work, the fields must stay in the
order defined by the programmer. However, if you’re creating a value type that has
nothing to do with interoperability with unmanaged code, you probably want to override
the C# compiler’s default. Here’s an example:
using System;
using System.Runtime.InteropService;
// Let the CLR arrange the fields to improve performance for this
// value type.
[StructLayout(LayoutKind.Auto)]
struct Point {
Int32 x, y;
}

Advertisements

Written by oneil

September 13, 2008 at 3:27 am

Posted in Framework

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: