C# Return different types?
I have a method which returns different types of instances (classes):
public [What Here?] GetAnything()
{
Hello hello = new Hello();
Computer computer = new Computer();
Radio radio = new Radio();
return radio; or return computer; or return hello //should be possible?!
}
How can I do this and later work with the variables, e.g. radio.Play()
, etc?
Do I need to use generics, and if so, how?
Solution 1:
Here is how you might do it with generics:
public T GetAnything<T>()
{
T t = //Code to create instance
return t;
}
But you would have to know what type you wanted returned at design time. And that would mean that you could just call a different method for each creation...
Solution 2:
If there is no common base-type or interface, then public object GetAnything() {...}
- but it would usually be preferable to have some kind of abstraction such as a common interface. For example if Hello
, Computer
and Radio
all implemented IFoo
, then it could return an IFoo
.
Solution 3:
use the dynamic keyword as return type.
private dynamic getValuesD<T>()
{
if (typeof(T) == typeof(int))
{
return 0;
}
else if (typeof(T) == typeof(string))
{
return "";
}
else if (typeof(T) == typeof(double))
{
return 0;
}
else
{
return false;
}
}
int res = getValuesD<int>();
string res1 = getValuesD<string>();
double res2 = getValuesD<double>();
bool res3 = getValuesD<bool>();
// dynamic keyword is preferable to use in this case instead of an object type
// because dynamic keyword keeps the underlying structure and data type so that // you can directly inspect and view the value.
// in object type, you have to cast the object to a specific data type to view // the underlying value.
regards,
Abhijit
Solution 4:
Marc's answer should be the correct one, but in .NET 4 you couldn't also go with dynamic type.
This should be used only if you have no control over the classes you return and there are no common ancestors ( usually with interop ) and only if not using dynamic is a lot more painful then using(casting every object in every step :) ).
Few blog post trying to explain when to use dynamic: http://blogs.msdn.com/b/csharpfaq/archive/tags/dynamic/
public dynamic GetSomething()
{
Hello hello = new Hello();
Computer computer = new Computer();
Radio radio = new Radio();
return // anyobject
}