Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Type Conversions

Tags:

c#

.net

casting

I am trying to convert an object to a generic type. Here is an example method:

void Main()
{
    object something = 4;
    Console.WriteLine(SomeMethod<int>(something));
    Console.WriteLine(SomeMethod<string>(something));
}

public T SomeMethod<T>(object someRandomThing)
{

    T result = Convert.ChangeType(someRandomThing, typeof(T));

    return result;
}

This gives this error:

Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?)

I have tried several variations to get my result cast as the generic type, but it is not working out each time.

Is there a way to make this cast?

NOTE: In my real example I am getting an "object" back from a stored procedure. The method could call one of several stored procedures, so the result could be a string or a int (or long) depending on which sproc is called.

like image 771
Vaccano Avatar asked Mar 28 '14 18:03

Vaccano


1 Answers

Convert.ChangeType returns object so you will need to cast the result back to a T

T result = (T)Convert.ChangeType(someRandomThing, typeof(T))
like image 64
Trevor Pilley Avatar answered Oct 12 '22 22:10

Trevor Pilley