Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting numerical concrete type to numerical generic type

Tags:

c#

generics

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).

like image 873
Vitor Py Avatar asked Jan 11 '11 18:01

Vitor Py


1 Answers

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.

like image 94
Jon Skeet Avatar answered Nov 04 '22 04:11

Jon Skeet