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
public static T MyMethod<T>() {
if ( typeof(T) == typeof(Int32) ) {
return (T)(object)0;
} else {
return (T)(object)"nothing";
}
}
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 given T. It is unbounded after all. So just tell the compiler explicitly it's not safe with casting to object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With