Why does C# not contain IParsable<T> or ITryParsable<T>?

Viewed 1303

Edit: Clearly this is not possible as C# does not allow static methods in interfaces.

Obviously it would be fairly simple to implement the following interfaces for your own solution

public interface IParsable<T>
{
    T Parse(string s);
}

public interface ITryParsable<T> : IParsable<T>
{
    bool TryParse(string s, out T output);
}

Having been writing various ways of parsing unknown typed user input data, I would have found having int, decimal, etc, etc implement a version of these interfaces indispensable.

To me it seems like a fairly obvious thing to have included in the System namespace.

Obviously this is not the case. So what is the best way of seeing whether a class "implements" these interfaces?

Checking whether the method exists via Duck Typing seems like a sensible alternative, but Reflection isn't terribly performant.

2 Answers

With .NET 6 Preview Generic Math, this does exist!

Parse and TryParse are in the new INumber interface

Related