Skip to content

Clarify sizeof rules for unsafe code blocks#51543

Open
BillWagner wants to merge 3 commits intodotnet:mainfrom
BillWagner:sizeof-reference-fixes
Open

Clarify sizeof rules for unsafe code blocks#51543
BillWagner wants to merge 3 commits intodotnet:mainfrom
BillWagner:sizeof-reference-fixes

Conversation

@BillWagner
Copy link
Member

@BillWagner BillWagner commented Feb 6, 2026

Some rules regarding nint, nuint, and ref struct types wasn't as clear as it should be. Add examples for nint, nuint, and Span<T>.

Fixes #51281


Internal previews

📄 File 🔗 Preview link
docs/csharp/language-reference/operators/sizeof.md sizeof operator - determine the memory needs for a given type

Some rules regarding nint, nuint, and ref struct types wasn't as clear as it should be.

Fixes dotnet#51281
@BillWagner BillWagner requested a review from a team as a code owner February 6, 2026 16:43
Copilot AI review requested due to automatic review settings February 6, 2026 16:43
@dotnetrepoman dotnetrepoman bot added this to the February 2026 milestone Feb 6, 2026
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This pull request clarifies the documentation for the sizeof operator, specifically addressing issue #51281 regarding the rules for using sizeof with different types in safe and unsafe code contexts. The changes improve accuracy by explicitly stating that nint, nuint, and ref struct types like Span<T> require unsafe context, and provide concrete examples demonstrating their usage.

Changes:

  • Updated documentation to clarify that safe code requires built-in unmanaged types whose size is not platform-dependent
  • Rewrote the unsafe code section with more precise descriptions of how sizeof works with different type categories
  • Added code examples demonstrating sizeof with nint, nuint, and Span<int> in unsafe blocks

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
docs/csharp/language-reference/operators/sizeof.md Updated documentation to clarify platform-dependent type restrictions and unsafe code rules, with improved descriptions of reference, value, and ref struct type behavior
docs/csharp/language-reference/operators/snippets/shared/SizeOfOperator.cs Added three new examples within the unsafe block demonstrating sizeof usage with nint, nuint, and Span<int>

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@BillWagner BillWagner requested a review from adegeo February 6, 2026 16:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sizeof operator description is incorrect w.r.t. constant-ness and managed-ness

1 participant