dotnet / dotnet/dotnet-api-docs

Incorrect alignment description about Decimal type

Open
#9,800 3 comments 0 reactions 0 assignees View on GitHub
area-System.Runtime Pri3 untriaged
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

The doc
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.structlayoutattribute.pack?view=net-8.0#code-try-6
says:
> To take another example, consider the following structure, which consists of two byte fields, one 32-bit signed integer field, one single-element byte array, and a decimal value. With the default packing size, the size of the structure is 28 bytes. The two bytes occupy the first two bytes of memory, followed by two bytes of padding, followed by the integer. Next is the one-byte array, followed by three bytes of padding. Finally, the [Decimal](https://learn.microsoft.com/en-us/dotnet/api/system.decimal?view=net-8.0) field, d5, aligns on a 4-byte boundary because a decimal value consists of four [Int32](https://learn.microsoft.com/en-us/dotnet/api/system.int32?view=net-8.0) fields, so its alignment is based on the size of the largest of its fields rather than on the size of the [Decimal](https://learn.microsoft.com/en-us/dotnet/api/system.decimal?view=net-8.0) structure as a whole.

```cs
using System;
using System.Runtime.InteropServices;

unsafe struct ExampleStruct2
{

public byte b1;
public byte b2;
public int i3;
public fixed byte a4[1];
public decimal d5;
}

public class Example
{
public unsafe static void Main()
{

ExampleStruct2 ex = new ExampleStruct2();
byte* addr = (byte*) &ex;
Console.WriteLine("Size: {0}", sizeof(ExampleStruct2));
Console.WriteLine("b1 Offset: {0}", &ex.b1 - addr);
Console.WriteLine("b2 Offset: {0}", &ex.b2 - addr);
Console.WriteLine("i3 Offset: {0}", (byte*) &ex.i3 - addr);
Console.WriteLine("a4 Offset: {0}", ex.a4 - addr);
Console.WriteLine("d5 Offset: {0}", (byte*) &ex.d5 - addr);
}
}
// The example displays the following output:
// Size: 28
// b1 Offset: 0
// b2 Offset: 1
// i3 Offset: 4
// a4 Offset: 8
// d5 Offset: 12
```

In fact, the sample code prints (tested on .NET 6 and .NET 8)
```
// Size: 32
// b1 Offset: 0
// b2 Offset: 1
// i3 Offset: 4
// a4 Offset: 8
// d5 Offset: 16
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.