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?
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
You can specify one or more constraints on the generic type using the where clause after the generic type name. The following example demonstrates a generic class with a constraint to reference types when instantiating the generic class.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
Multiple interface constraints can be specified. The constraining interface can also be generic.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With