Reputation: 165
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.
Upvotes: 12
Views: 8623
Reputation: 389
int x = (dynamic)MyTest.Value;
I know this is a very old thread, but this is the actual way to do it. (dynamic)
will convert the T value to any of the primitive known type in runtime.
Upvotes: 3
Reputation: 321
int id = (dynamic)myobject.SingleOrDefault();
OR
int id = (int)myobject.SingleOrDefault();
It worked for me to get the int
value. Here myobject
is having ObjectResult<Nullable<int>>
value.
Upvotes: 0
Reputation: 71
See my answer to another post: https://stackoverflow.com/a/26098316/1458303. It contains an effective class implementation which avoids boxing during conversion.
Upvotes: 0
Reputation: 1500485
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.
Upvotes: 15
Reputation: 15559
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);
}
}
}
Upvotes: 1