// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This extension is restricted to the .NET 6 because it shares the same BCL // across all targets, ensuring that the layout of our Nullable mapping type // will be correct. Exposing this API on older targets (especially .NET Standard) // is not guaranteed to be correct and could result in invalid memory accesses. #if NET6_0_OR_GREATER using System; using System.Runtime.CompilerServices; namespace CommunityToolkit.HighPerformance; /// /// Helpers for working with the type. /// public static class NullableExtensions { /// /// Returns a reference to the value of the input instance, regardless of whether /// the property is returning or not. If that is not /// the case, this method will still return a reference to the underlying value. /// /// The type of the underlying value. /// The . /// A reference to the underlying value from the input instance. /// /// Note that attempting to mutate the returned reference will not change the value returned by . /// That means that reassigning the value of an empty instance will not make return . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T DangerousGetValueOrDefaultReference(this ref T? value) where T : struct { return ref Unsafe.As>(ref value).Value; } /// /// Returns a reference to the value of the input instance, or a reference. /// /// The type of the underlying value. /// The . /// A reference to the value of the input instance, or a reference. /// The returned reference can be tested for using . [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe ref T DangerousGetValueOrNullReference(ref this T? value) where T : struct { if (value.HasValue) { return ref Unsafe.As>(ref value).Value; } return ref Unsafe.NullRef(); } /// /// Mapping type that reflects the internal layout of the type. /// See https://github.com/dotnet/runtime/blob/master/src/libraries/System.Private.CoreLib/src/System/Nullable.cs. /// /// The value type wrapped by the current instance. private struct RawNullableData where T : struct { #pragma warning disable CS0649 // Unassigned fields public bool HasValue; public T Value; #pragma warning restore CS0649 } } #endif