docs icon indicating copy to clipboard operation
docs copied to clipboard

Doc page for sizeof operator incorrectly states that sizeof(T) may be used in safe code when T is constrained to be unmanaged

Open Quogu opened this issue 1 week ago • 0 comments

Type of issue

Other (describe below)

Description

The documentation reads:

In safe code, the argument to the sizeof operator must be the name of an unmanaged type or a type parameter that is constrained to be an unmanaged type.

This is incorrect, however - the following code demonstrates that a type parameter that's constrained to be an unmanaged type may not have sizeof applied to it in safe code:

public class Foo
{
    public int GetSize<T>() where T : unmanaged
    {
        return sizeof(T);
    }
}
// error CS0233: 'T' does not have a predefined size, therefore sizeof can only be used in an unsafe context

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#unmanaged-constraint correctly states, in contradiction to the above:

The preceding method must be compiled in an unsafe context because it uses the sizeof operator on a type not known to be a built-in type.

Please can the sizeof operator doc page be corrected?

Page URL

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/sizeof

Content source URL

https://github.com/dotnet/docs/blob/main/docs/csharp/language-reference/operators/sizeof.md

Document Version Independent Id

7e28a662-f550-d202-9a97-e684ae1b074d

Platform Id

86e8a1a6-0fd2-822f-93d0-d5ec8ddc72b0

Article author

@BillWagner

Metadata

  • ID: 191acdd8-8e36-8bd4-1172-140717c36a85
  • PlatformId: 86e8a1a6-0fd2-822f-93d0-d5ec8ddc72b0
  • Service: dotnet-csharp
  • Sub-service: lang-reference

Related Issues


Associated WorkItem - 537142

Quogu avatar Dec 01 '25 18:12 Quogu