Aleksey Bieneman
Aleksey Bieneman

Reputation: 165

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

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

Answers (7)

Irwin
Irwin

Reputation: 101

The following way should work.

int x = (int)(value as int?);

Upvotes: 0

c_str
c_str

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

waghekapil
waghekapil

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

Alexey Larchenko
Alexey Larchenko

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

Jon Skeet
Jon Skeet

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

dkackman
dkackman

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

driis
driis

Reputation: 164291

Convert.ToInt32(value); 

Should do it.

Upvotes: 2

Related Questions