Version Used: Roslyn 2.7.0 or master
Steps to Reproduce:
Try to compile the following code:
c#
struct S
{
int SizeOfS() => sizeof(S);
}
Actual Behavior:
error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
Expected Behavior:
Since Marshal.SizeOf() is not a direct replacement for sizeof(), maybe the error message should not mention it? On .Net Core, it could make sense to suggest Unsafe.SizeOf() instead, but that method is not available on .Net Framework or .Net Standard out of the box (it requires the System.Runtime.CompilerServices.Unsafe package), so maybe that suggestion should be removed altogether?
Rather than this error we should just allow sizeof in any context. There is really no reason to have this be unsafe only other than accident of history. I think we should just file a bug on csharplang to do this.
@jaredpar There are already issues for allowing sizeof for generic types constrained to struct https://github.com/dotnet/csharplang/issues/1032 and to unmanaged https://github.com/dotnet/csharplang/issues/1508. I didn't find one for always allowing it.
@svick i saw the same when I searched. I think we need a new issue to cover just blanket allowing it. I was surprised we didn't have on already.
Most helpful comment
Rather than this error we should just allow
sizeofin any context. There is really no reason to have this be unsafe only other than accident of history. I think we should just file a bug on csharplang to do this.