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.
source share