Skip to content

Commit 47b060a

Browse files
committed
Fix "3. Null managed pointers" section
1 parent 536ff99 commit 47b060a

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

docs/standard/unsafe-code/best-practices.md

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -625,23 +625,22 @@ The only correct approach is to use field-by-field loads/store specialized for e
625625

626626
## 13. Null managed pointers
627627

628-
While it is legal for a managed pointer to point to null (in much the same way that it's legal for a managed pointer to point just past the end of an array, see [ECMA-335 augments](#references)), it is not legal to _dereference_ such a pointer, and doing so results in undefined behavior.
629-
630-
There are various ways to generate a null byref, though none involve idiomatic C# code.
628+
Generally, byrefs (managed pointers) are rarely null and the only safe way to create a null byref as of today is
629+
to initialize a `ref struct` with `default`, then all its `ref` fields will be null managed pointers:
631630

632631
```cs
633-
// Null reference (not byref):
634-
object obj = null;
632+
RefStructWithRefField s = default;
633+
ref byte nullRef = ref s.refFld;
634+
```
635+
636+
However, there are several unsafe ways to create null byrefs, some examples include:
635637

638+
```cs
636639
// Null byref by calling Unsafe.NullRef directly:
637640
ref object obj = ref Unsafe.NullRef<object>();
638641

639642
// Null byref by turning a null unmanaged pointer into a null managed pointer:
640643
ref object obj = ref Unsafe.AsRef<object>((void*)0);
641-
642-
// Null byref without Unsafe API:
643-
RefStructWithRefField s = default;
644-
ref byte nullRef = ref s.refFld;
645644
```
646645

647646
The risk of introducing memory safety issues is admittedly low, since with modern .NET runtimes, any attempt to dereference

0 commit comments

Comments
 (0)