Skip to content

bool does not implement IParsable<TSelf> #78523

@znakeeye

Description

@znakeeye

Description

I'm writing a parser and this one is quite problematic. For the most basic type, a boolean, the new IParsable<TSelf> interface is not available. This makes no sense.

I realize that there is little need for a bool.Parse(string, IFormatProvider?) but since the second parameter may be null, it would be a no-brainer to implement. See Boolean.cs(228). Just add the interface, and these methods:

public static bool Parse(string value, IFormatProvider? _) => Parse(value);
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? _, [MaybeNullWhen(false)] out TSelf result)
{
    return TryParse(s, out result);
}

Reproduction Steps

Running VS 17.5 targeting .NET 7.0, simply create a console app with the code below.

internal class Program
{
    static void Main(string[] args)
    {
        Cast<int>("123");   // OK
        Cast<bool>("true"); // CS0315
    }

    public static TSelf Cast<TSelf>(string s) where TSelf : IParsable<TSelf> => TSelf.Parse(s, null);
}

Expected behavior

Boolean implements IParsable<TSelf>, just like all other primitive types.

Actual behavior

Boolean does not implement IParsable<TSelf>.

Regression?

No

Known Workarounds

Wherever a method expects IParsable<T> you can duplicate that method to handle bool specifically. E.g.:

internal class Program
{
    static void Main(string[] args)
    {
        Cast<int>("123");
        CastBool("true"); // CS0315
    }

    public static TSelf Cast<TSelf>(string s) where TSelf : IParsable<TSelf> => TSelf.Parse(s, null);
    public static bool CastBool(string s) => bool.Parse(s);
}

Configuration

.NET 7.0
Windows 11 (x64)

Other information

https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Boolean.cs#L24

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions