How to convert value of Generic Type Argument to a concrete type?
- by Aleksey Bieneman
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!