.NET 7 recently introduced IParsable as an interface, and I'd like to check for its presence. Some test that will return true if T implements IParsable<T> and false otherwise.
Say I want to return an object that is of type T when T has a Parse method, for example:
T ParseAs<T>(string s)
{
if (typeof(IParsable<T>).IsAssignableFrom(typeof(T)))
{
return T.Parse(s);
}
else
{
//do something else...
}
}
I would hope this to check if T implements IParsable<T> and grant me access to the Parse and TryParse methods inside. I don't seem to be able to use T as a type argument for IParsable, instead receiving this exception:
CS0314
The type 'T' cannot be used as type parameter 'TSelf' in the generic type or method 'IParsable<TSelf>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IParsable<T>'
I also receive the above error if I try to use is:
s is IParsable<T>
How would I resolve this?