Search code examples
c#clrnullablecustom-attributes

Why does the `System.Nullable<T>` type has the `StructLayout(LayoutKind.Sequential)` attribute?


Why does the System.Nullable<T> type has the StructLayout(LayoutKind.Sequential) attribute?

I found the following piece of text and code in the CLR via C# book:

Here is the logical representation of how the System.Nullable type is defined:

[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Nullable<T> where T : struct { 
   //... unrelated to the question code
}

So, why is it logical for the System.Nullable<T> to have the StructLayout(LayoutKind.Sequential) attribute being applied? I believe that it would be enough to answer my question if someone would just explain for what case (or cases) was the attribute added (i.e. what purpose does it serve).

I understand what the attribute does. I do not understand why is it necessary to have the attribute for the System.Nullable<T> type.


Solution

  • It doesn't actually have that attribute. If it used to when the book was written, it doesn't anymore.

    You can see this for yourself for .NET Framework (source here):

        [Serializable]
        [System.Runtime.Versioning.NonVersionable] // This only applies to field layout
        public struct Nullable<T> where T : struct
        {
    

    and for .NET Core (source here):

        [Serializable]
        [NonVersionable] // This only applies to field layout
        [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
        public partial struct Nullable<T> where T : struct
        {