views:

140

answers:

3

I am trying to convert the value of the generic type parameter T value into integer after making sure that T is in fact integer:

public class Test
{
    void DoSomething<T>(T value)
    {
        var type = typeof(T);
        if (type == typeof(int))
        {
            int x = (int)value; // Error 167 Cannot convert type 'T' to 'int'
            int y = (int)(object)value; // works though boxing and unboxing
        }
    }
}

Although it works through boxing and unboxing, this is an additional performance overhead and i was wandering if there's a way to do it directly.

Thank you!

+1  A: 
Convert.ToInt32(value); 

Should do it.

driis
+6  A: 

Boxing and unboxing is going to be the most efficient way here, to be honest. I don't know of any way of avoiding the boxing occurring, and any other form of conversion (e.g. Convert.ToInt32) is potentially going to perform conversions you don't actually want.

Jon Skeet
Thank you for confirming my thoughts on boxing/unboxing. Calling Convert would indeed be slower as there's an added overhead of calling as well as the boxing/unboxing that would occur anyway: Convert.ToInt32(object value) takes object so T would be boxed at this point and then unboxed at some point later.
Aleksey Bieneman
A: 

int and the other CLR primitives implement IConvertible.

public class Test
{
    void DoSomething<T>(T value) where T : IConvertible
    {
        var type = typeof(T);
        if (type == typeof(int))
        {
            int y = value.ToInt32(CultureInfo.CurrentUICulture);
        }
    }
}
dkackman