I would like to know if there's a specific constraint for numerical types that allows casting to work in the following case:
class MyClass<T>
{
...
void MyMethod()
{
....
byte value = AnotherObject.GetValue()
Tvalue = (T)value;
....
}
...
}
I tried boxing and unboxing like:
Tvalue = (T)(object)value;
But this only works if T == byte
. Otherwise I get an InvalidCastException
.
T is always a number type (like short, float, and so on).
Yes, you can only unbox a value to the same type.
Have you tried using
Tvalue = (T) Convert.ChangeType(value, typeof(T));
? Here's a sample:
using System;
class Test
{
static void Main()
{
TestChange<int>();
TestChange<float>();
TestChange<decimal>();
}
static void TestChange<T>()
{
byte b = 10;
T t = (T) Convert.ChangeType(b, typeof(T));
Console.WriteLine("10 as a {0}: {1}", typeof(T), t);
}
}
There's no constraint here, although you could specify
where T : struct, IComparable<T>
as a first pass. That constraint has nothing to do with the conversion working though - it would just be to attempt to stop callers from using an inappropriate type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With