Could I have something like this:
int x = MyMethod<int>();
string y = MyMethod<string>();
So, one method returning different types based on T. Of course, there would be logic inside the method to ensure it was returning the correct thing.
I can never get something like this to run. It complains that it can’t cast the return value to T:
public static T MyMethod<T>()
{
if(typeof(T) == typeof(Int32))
{
return 0;
}
else
{
return "nothing";
}
}
Try the following
The trick here is the casting to
object. What you are trying to do is inherently unsafe since the compiler cannot infer that 0 or “nothing” are convertible to any givenT. It is unbounded after all. So just tell the compiler explicitly it’s not safe with casting toobject.