Skip to content

[API Proposal]: Change the nullable annotation of IParsable.TryParse / ISpanParsable.TryParse #71309

@meziantou

Description

@meziantou

Background and motivation

It's common for TryParse methods to set the out parameter to null when returning false. The current IParsable / ISpanParsable doesn't allow null values. I think the interface should add [MaybeNullWhen(false)] to the out parameter.

API Proposal

namespace System;

public interface ISpanParsable<T>
{
    // existing
    static abstract bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, out TSelf result);

    // suggested
    static abstract bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, [MaybeNullWhen(false)]out TSelf result);
}

public interface IParsable<T>
{
    // existing
    static abstract bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, out TSelf result);

    // suggested
    static abstract bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [MaybeNullWhen(false)]out TSelf result);
}

API Usage

public class Sample : ISpanParsable<Sample>
{
    public static Sample Parse(string s, IFormatProvider? provider) => new Sample();
    public static Sample Parse(ReadOnlySpan<char> s, IFormatProvider? provider) => new Sample();

    public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, out Sample result)
    {
        result = default; // should be valid
        return false;
    }

    public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, out Sample result)
    {
        result = default; // should be valid
        return false;
    }
}

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.RuntimeblockingMarks issues that we want to fast track in order to unblock other important work

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions