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?
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...
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
.
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