How to convert value of Generic Type Argument to a concrete type?
Posted
by Aleksey Bieneman
on Stack Overflow
See other posts from Stack Overflow
or by Aleksey Bieneman
Published on 2010-05-19T16:52:38Z
Indexed on
2010/05/19
17:00 UTC
Read the original article
Hit count: 198
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!
© Stack Overflow or respective owner