Description
Use ref *(T*)null
instead of Unsafe.NullRef<T>()
to save 3 bytes of IL (sharplab).
Slightly smaller IL size (saves 3 bytes) an most importantly avoids a generic type instantiation. Could also potentially help the JIT in some niche cases, though it should handle
NullRef
well too given it's an intrinsic now. I'd also say conceptually it seems to meref *(T*)null
makes more sense in that theUnsafe
APIs were all added as a workaround for things that could not be done at all in C#. Now that C# can express this, there's no need to use the workaround API anymore. It's the same withUnsafe.SizeOf<T>
: now that you can just dosizeof(T)
everywhere, there's no need to ever use that either. Same thing forUnsafe.As
in some context, now that you can have pointers to managed types 🙂Like, if hypothetically speaking you could do everything you can do with
Unsafe
with just C#, you'd never useUnsafe
, and for the same reason if C# had always been able to express all of it,Unsafe
APIs would've never been added in the first place.
Originally posted by @Sergio0694 in #79589 (comment)