6
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?

dumbledad
  • 16,305
  • 23
  • 120
  • 273
  • 2
    That's duck typing. C# doesn't have that, except for some early weirdness with enumerables (and still some with awaitables) -- no custom duck typing, in any case. – Jeroen Mostert Nov 17 '17 at 10:53
  • How would this work anyway, even if it was possible? `TryParse()` is a static method, so what object would you pass? – Matthew Watson Nov 17 '17 at 10:57
  • 1
    You can't do this statically but you could add a parameter for a `TryParse` delegate and pass it explicitly i.e. `DoSomething("someString", double.TryParse);` – Lee Nov 17 '17 at 10:58
  • Maybe somehow related: https://stackoverflow.com/q/32664/579895 – Pikoh Nov 17 '17 at 11:00
  • On a related note, C# does have the general notion of "objects that can convert themselves", in the form of `IConvertible`, which is in turn used by `Convert`. This setup is not particularly efficient, and it won't allow you to constrain types to *just* the ones parseable as strings, nor is it even a guarantee that the object can convert itself from a string, and to top it all off there's no `Convert.TryChangeType` -- but it's something. I'd personally prefer the delegate approach. – Jeroen Mostert Nov 17 '17 at 11:09

1 Answers1

8

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.

Community
  • 1
  • 1
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • 1
    "Sorry. I don't know what else to say." You and me both. I was anxious that my question was too short. – dumbledad Nov 17 '17 at 11:11