Generic Type Conversions

.net, c#, casting

Solution

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

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

Problem

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.

Original source