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) { . .  } 
                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.
Yes an interface is a very valid return value.
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.
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!
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.
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