Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

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?

like image 592
dumbledad Avatar asked Nov 17 '17 10:11

dumbledad


People also ask

How do you restrict a generic type?

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.

How do you add generic constraints?

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.

What are the constraints in generics?

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.

Can a generic class have multiple constraints?

Multiple interface constraints can be specified. The constraining interface can also be generic.


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.

like image 187
nvoigt Avatar answered Oct 17 '22 23:10

nvoigt