How would I constrain a generic method in C# to only allow T where T has TryParse?

Viewed 78
public int DoSomething<T>(string someString)

I want to insist that I can call TryParse on T. Is it possible to restrict T in that way? TryParse is not part of an interface, it just seems to exist on a number of value types, so how would I do this?

1 Answers

You cannot

Sorry. I don't know what else to say. It's simply not possible. You could allow any T and then do reflection somewhere and throw if it does not have a method called TryParse but as it's not part of an interface or base class... there is no way.

Related