Differences in behaviour or usage between UnsafeUtility.SizeOf and sizeof

I am wondering what differences there are between UnsafeUtility.SizeOf and C#'s builtin sizeof.

One difference is that sizeof user-defined structs requires declaring the method unsafe.

Another potential one is that (iirc) sizeof inlines the size as a constant. I’d love to know what we can assume about UnsafeUtility.SizeOf in this regard. It’s easy to check the assembly and get one answer but that doesn’t give much info on expected behavior under different compilation environments (e.g. burst -v- dotnet) or compilation configurations (e.g. debug -v- release)

Thanks

The C# compiler does indeed inline sizeof as a constant for the predefined types listed here: Unsafe code - C# language specification | Microsoft Learn

For other types, the behaviour differs between Burst and Mono / IL2CPP:

  • Burst inlines sizeof (for user-defined types) and UnsafeUtility.Size as a constant.
  • In Mono and IL2CPP, both sizeof (for user-defined types) and UnsafeUtility.Size are calculated at runtime.
1 Like

Thanks @tim_jones , that’s exactly what I was after. Have a great day

2 Likes