How to constrain Generics to specific types?

S

Shmulik

Is there a way to constrain a Generics class to only accept specific value
types,
for instance, lets say I want to create a Histogram class that could accept
the types int, float, double, etc., but not char or string.

Is is possible to declare the class to do this?

class Histogram<T values> : constrain to {int, float, double}
{
....
Histogram<T v)
{
}

}
 
G

Guest

The 'where' keyword constrains generic types, although multiple constraints
are an "and" condition, not an "or" condition, for example:

class C<T> where T : IComparable, IEnumerable {}

IN that example T must implement both interfaces, so you can't really do
what you want. You could just write the class for the largest numeric type
you need (like decimal) then when you pass a smaller type it will be
implicitly cast up.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top