U
Udi
Hi All,
Two questions regarding Generics:
1. I'd like to constrain my Type parameter to be one of a preefined
group of types. For example:
class Field<T> where T: Byte, Int, String, Array<byte> {}
- Meaning T can by either Byte, Int String or Array<byte>.
Is there a way to force a type to this constraint?
2. I have a buffer that represents one of the above types.
I'd like to add a method to get the value from the buffer.
I was hoping to do something like this:
public T GetFieldValue(byte [] buffer)
{
switch(fieldType)
{
case byte:
{
return buffer[offset]; //Error can't cast
byte to T
}
case int:
{
return (T)BitConverter.ToInt32(buffer, offset); //
Error can't cast int to T
}
:
:
}
}
The problem is that the compiler can't cast from my type to T.
Any ideas on how to solve this?
(I would like to prevent the caller to GetFieldValue() from using
another switch/case statement on result type.)
Thanks!
Udi.
Two questions regarding Generics:
1. I'd like to constrain my Type parameter to be one of a preefined
group of types. For example:
class Field<T> where T: Byte, Int, String, Array<byte> {}
- Meaning T can by either Byte, Int String or Array<byte>.
Is there a way to force a type to this constraint?
2. I have a buffer that represents one of the above types.
I'd like to add a method to get the value from the buffer.
I was hoping to do something like this:
public T GetFieldValue(byte [] buffer)
{
switch(fieldType)
{
case byte:
{
return buffer[offset]; //Error can't cast
byte to T
}
case int:
{
return (T)BitConverter.ToInt32(buffer, offset); //
Error can't cast int to T
}
:
:
}
}
The problem is that the compiler can't cast from my type to T.
Any ideas on how to solve this?
(I would like to prevent the caller to GetFieldValue() from using
another switch/case statement on result type.)
Thanks!
Udi.