Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Return different types?

Tags:

c#

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?

like image 238
eMi Avatar asked Jan 24 '12 12:01

eMi


2 Answers

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

like image 176
RQDQ Avatar answered Oct 14 '22 16:10

RQDQ


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.

like image 36
Marc Gravell Avatar answered Oct 14 '22 18:10

Marc Gravell