Skip to content

API proposal: Nullable.RefValue, RefValueOrDefault #1534

@nagya

Description

@nagya

EDIT: @stephentoub's proposal update from #1534 (comment) on 1/29/2022:

namespace System
{
    public static class Nullable
    {
+        public static ref readonly T GetValueRefOrDefaultRef<T>(in T? nullable) where T : struct => ref nullable.value;
    }
}

Proposed API

namespace System
{
    public static class Nullable
    {
        public static ref readonly T RefValue<T>(this in T? n) where T : struct;
        public static ref readonly T RefValueOrDefault<T>(this in T? n) where T : struct;
        public static ref readonly T RefValueOrDefault<T>(this in T? n, in T defaultValue) where T : struct;
    }
}

These parallel the Value property and the GetValueOrDefault methods of Nullable<T>, but return the value by reference. They're extension methods because of CS8170: Struct members cannot return 'this' or other instance members by reference.

They're useful for accessing the value wrapped by a Nullable<T> without incurring a copy.

Reference implementation

namespace System
{
    public static class Nullable
    {
        public static ref readonly T RefValue<T>(this in T? n) where T : struct
        {
            if (n.HasValue)
                return ref n.value;
            else
                throw new InvalidOperationException();
        }

        public static ref readonly T RefValueOrDefault<T>(this in T? n) where T : struct
        {
            return ref n.value;
        }
        
        public static ref readonly T RefValueOrDefault<T>(this in T? n, in T defaultValue) where T : struct
        {
            return ref n.HasValue ? ref n.value : ref defaultValue;
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions