generic with constraint of type int

  • Thread starter Thread starter Dan Holmes
  • Start date Start date
D

Dan Holmes

I have a class that i need a constraint of int, string, float or bool. I
have tried the following but can't make VS accept it. I read the docs
and they showed that any value type can be used unless it is nullable.
Why doesn't this work?

public class Metadata<T>
where T: System.int


line from the docs
where T: struct
The type argument must be a value type. Any value type except Nullable
can be specified. See Using Nullable Types (C# Programming Guide) for
more information.


dan
 
It means exactly what it says. If you have class Metadata<T> where T: struct

then you can have

Metadata<int>
Metadata<float>
Metadata<bool>
etc.
but you would not be able to have e.g. Metadata<Nullable<int>>,
neither would you be able to have Metadata<string> because string is a
reference type.

You would not be able to have a constraint which restricts to only int,
float, string and bool. The legal values for constraints are listed here:
http://msdn2.microsoft.com/en-us/library/d5x73970(VS.80).aspx

======================
Clive Dixon
Digita Ltd. (www.digita.com)
 
Dan Holmes said:
I have a class that i need a constraint of int, string, float or bool.

You cannot express such a constraint using generic constraints. You'll
need to put an imperative test in the constructor.

Do for example:

---8<---
class A<T>
{
public A()
{
if (!(T is Int32) || // ... etc.
}
}
--->8---
Why doesn't this work?

public class Metadata<T>
where T: System.int

A new type cannot descend from an existing value type, so this
constraint would restrict the generic type to exactly one possible
instantiation said:
line from the docs
where T: struct
The type argument must be a value type. Any value type except Nullable
can be specified. See Using Nullable Types (C# Programming Guide) for
more information.

This documentation is describing the literal constraint 'where T:
struct'. The 'struct' in this constraint description is not a
placeholder. The 'where T: struct' constraint constrains the type
parameter to be a value type other than nullable.

-- Barry
 
What is the best way to handle this? Check the type of T in the
constructor and throw if T isn't one of the valid types?

dan
 
That's the only way I can see of doing what you want, though it isn't ideal
since you're only catching at runtime and not at compile time.
 
A better way to do it (although not ideal, because like the other it is
not caught at compile time) would be to check the type in the static
constructor, since that is done only once.

Hope this helps.
 
Back
Top