Skip to content

Replace Unsafe.NullRef<T>() usage #80107

Closed
@xtqqczze

Description

@xtqqczze

Use ref *(T*)nullinstead 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 me ref *(T*)null makes more sense in that the Unsafe 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 with Unsafe.SizeOf<T>: now that you can just do sizeof(T) everywhere, there's no need to ever use that either. Same thing for Unsafe.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 use Unsafe, 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)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions