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.
Swift 4 language provides 'Generic' features to write flexible and reusable functions and types. Generics are used to avoid duplication and to provide abstraction. Swift 4 standard libraries are built with generics code. Swift 4s 'Arrays' and 'Dictionary' types belong to generic collections.
Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.
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.
Convert.ToInt32(value);
Should do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With