generics - constraint

M

Michael Moreno

hello,

I am trying to write a generic class where the underlying type is
either an int, a float or a double:

public class CMatrix<T>: ICloneable where VarType: int, float, double

but that does not compile.

The error message is :

'int' is not a valid constraint. A type used as a constraint must be an
interface, a non-sealed class or a type parameter.

Is it possible to do what I want?

thanks.
 
J

Jesse McGrew

Michael said:
I am trying to write a generic class where the underlying type is
either an int, a float or a double:

public class CMatrix<T>: ICloneable where VarType: int, float, double

but that does not compile.

The error message is :

'int' is not a valid constraint. A type used as a constraint must be an
interface, a non-sealed class or a type parameter.

Is it possible to do what I want?

No, I think the best you can do is write a static constructor that
checks typeof(T) and throws an exception if it isn't int, float, or
double.

Jesse
 
M

Michael Moreno

No, I think the best you can do is write a static constructor that
checks typeof(T) and throws an exception if it isn't int, float, or
double.

Thanks. Generics are very limited then because you cannot perform any
operator >, <, +, -, *, / in the code.
I hope they will fix that!
 

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