C# Return Different Types?
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
.
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...
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