Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraining a generic type argument to numeric types

Tags:

c#

generics

I'm defining a generic type:

public class Point<T> where T : IConvertible, IComparable

What I would really like to do is constrain T to be a numeric type (one of the ints or floats.) There's no INumeric in the CLR. Is there an interface or collection of interfaces that could be used here to constrain the type to one of the boxed numeric classes?

like image 394
Yes - that Jake. Avatar asked Nov 16 '11 18:11

Yes - that Jake.


2 Answers

Unfortunately, no. This has been a highly requested feature for a long time.

Right now, the best option is likely to use:

where T : struct, IConvertible, IComparable<T>

(The struct constraint prevents string usage...)

However, this still allows any user defined value type that implements the appropriate constraints to be used.

like image 94
Reed Copsey Avatar answered Nov 14 '22 23:11

Reed Copsey


where T: struct will constrain it to a value type.

like image 38
Garrett Vlieger Avatar answered Nov 14 '22 22:11

Garrett Vlieger