Determining if a type is IParsable, and invoking Parse #77454
-
I'm experimenting with some of the new types in .NET 7 and syntax in C# 11. Specifically I was trying to determine in a generic method whether a provided type T is parsable so it can be read using the bool Test<T>()
{
var dummy = new T(); // Don't know if can be tested without this dummy
// Obviously, this is invalid syntax
return T is IParsable<T>;
// This results in an error, as T have not enough information about being IParsable<T>,
// and also IParsable is defined recursively: interface IParsable<T> where T : IParsable<T>
return dummy is IParsable<T>;
// Some way of doing this without reflection? Or at least, as performant as possible?
return typeof(T).GetInterface("IParsable`1") is not null);
} The goal I had was test the type (unconstrained) and, if parsable, call a specific method that calls Another doubt I have is, whenever I somehow have determined that T is parsable, how do I call I've already discussed this with several people in the C# Discord server, and the consensus is that it can't be done without reflection. I wanted to confirm here with people more knowledgeable in the runtime and the new types. Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
This is a limitation of the language with a small proposal on how it could be handled here: dotnet/csharplang#6308 Such a language feature may also require runtime work. |
Beta Was this translation helpful? Give feedback.
This is a limitation of the language with a small proposal on how it could be handled here: dotnet/csharplang#6308
Such a language feature may also require runtime work.