Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interface as return type

Tags:

c#

interface

Can interface be a return type of a function. If yes then whats the advantage. e.g. is the following code correct where array of interface is being returned.

public interface Interface {     int Type { get; }     string Name { get; } }  public override Interface[] ShowValue(int a) { . .  } 
like image 468
saam Avatar asked Mar 13 '13 17:03

saam


People also ask

Can we use interface as return type in Java?

Since an interface provides all of that, you can call methods on it, just as you can on a regular class. Of course, in order for the method to actually return some object, there needs to be some class that implements that interface somewhere.

Can an interface return a value?

Yes an interface is a very valid return value.

Can we use interface as data type?

You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.


2 Answers

Yes, you can return an interface.

Let's say classes A and B each implement interface Ic:

public interface Ic {     int Type { get; }     string Name { get; } }  public class A : Ic {      .      .      . }  public class B : Ic      .      .      . }  public Ic func(bool flag) {      if (flag)          return new A();        return new B();  } 

In this example func is like factory method — it can return different objects!

like image 74
One Man Crew Avatar answered Oct 04 '22 06:10

One Man Crew


Yes an interface is a very valid return value. Remember, you're not returning the definition of the interface, but rather an instance of that interface.

The benefit is very clear, consider the following code:

public interface ICar {     string Make { get; } }  public class Malibu : ICar {     public string Make { get { return "Chevrolet"; } } }  public class Mustang : ICar {     public string Make { get { return "Ford"; } } } 

now you could return a number of different ICar instances that have their own respective values.

But, the primary reason for using interfaces is so that they can be shared amongst assemblies in a well-known contract so that when you pass somebody an ICar, they don't know anything about it, but they know it has a Make. Further, they can't execute anything against it except the public interface. So if Mustang had a public member named Model they couldn't get to that unless it was in the interface.

like image 34
Mike Perrenoud Avatar answered Oct 04 '22 08:10

Mike Perrenoud