Yes - that Jake.
Yes - that Jake.

Reputation: 17119

Constraining a generic type argument to numeric types

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?

Upvotes: 5

Views: 1655

Answers (4)

Reed Copsey
Reed Copsey

Reputation: 564451

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.

Upvotes: 11

Michael B
Michael B

Reputation: 7577

No you can't do it. You can choose where T:struct,IConvertible,IFormattable,IComparable to restrict it to all blittable numeric types and enums, but even if you did the restriction you still can't use operators on T as the operators are all static.

E.g.

point.X-point.Y

Would be illegal as generics don't know about static members.

Upvotes: 0

Fischermaen
Fischermaen

Reputation: 12458

One - not very comfortable way - is to check the valid type in the constructor and throw an exception. It works, but it isn't "compiler-safe" and produces runtime errors. :-(

Upvotes: 1

Garrett Vlieger
Garrett Vlieger

Reputation: 9494

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

Upvotes: 1

Related Questions