Skip to content

Commit 7e56365

Browse files
committed
Use Nullable.GetValueRefOrDefaultRef where possible
1 parent 9fc1027 commit 7e56365

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

CommunityToolkit.HighPerformance/Extensions/NullableExtensions.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,11 @@ public static class NullableExtensions
3535
public static ref T DangerousGetValueOrDefaultReference<T>(this ref T? value)
3636
where T : struct
3737
{
38+
#if NET7_0_OR_GREATER
39+
return ref Unsafe.AsRef(in Nullable.GetValueRefOrDefaultRef(in value));
40+
#else
3841
return ref Unsafe.As<T?, RawNullableData<T>>(ref value).Value;
42+
#endif
3943
}
4044

4145
/// <summary>
@@ -51,12 +55,17 @@ public static unsafe ref T DangerousGetValueOrNullReference<T>(ref this T? value
5155
{
5256
if (value.HasValue)
5357
{
58+
#if NET7_0_OR_GREATER
59+
return ref Unsafe.AsRef(in Nullable.GetValueRefOrDefaultRef(in value));
60+
#else
5461
return ref Unsafe.As<T?, RawNullableData<T>>(ref value).Value;
62+
#endif
5563
}
5664

5765
return ref Unsafe.NullRef<T>();
5866
}
5967

68+
#if !NET7_0_OR_GREATER
6069
/// <summary>
6170
/// Mapping type that reflects the internal layout of the <see cref="Nullable{T}"/> type.
6271
/// See https://github.com/dotnet/runtime/blob/master/src/libraries/System.Private.CoreLib/src/System/Nullable.cs.
@@ -70,6 +79,7 @@ private struct RawNullableData<T>
7079
public T Value;
7180
#pragma warning restore CS0649
7281
}
82+
#endif
7383
}
7484

7585
#endif

0 commit comments

Comments
 (0)