Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generic methods, is it possible to get different types back from the same method?

Tags:

c#

generics

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";
  }
}
like image 625
Deane Avatar asked Jan 22 '10 21:01

Deane


1 Answers

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.

like image 164
JaredPar Avatar answered Oct 05 '22 03:10

JaredPar