Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert value of Generic Type Argument to a concrete type?

Tags:

c#

.net

generics

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.

like image 511
Aleksey Bieneman Avatar asked May 19 '10 16:05

Aleksey Bieneman


People also ask

How to define generic function in Swift?

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.

What is generic class in oops?

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.


2 Answers

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.

like image 87
Jon Skeet Avatar answered Sep 29 '22 03:09

Jon Skeet


Convert.ToInt32(value); 

Should do it.

like image 31
driis Avatar answered Sep 29 '22 04:09

driis