Generic Conversions

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:

It is not possible to implicitly convert the type 'object' to 'T'. Explicit conversion exists (are you skipping listing?)

I tried several options to get the result as a generic type, but it does not work every time.

Is there any way to do this?

NOTE. In my actual example, I am returning an “object” from a stored procedure. A method can call one of several stored procedures, so the result can be a string or int (or long), depending on which call sproc called.

+6
source share
2 answers

Convert.ChangeType returns an object, so you need to return the result back to T

 T result = (T)Convert.ChangeType(someRandomThing, typeof(T)) 
+11
source

try the following:

 return (T)Convert.ChangeType(someRandomThing, typeof(T)); 
+3
source

All Articles