Interface

From Logic Wiki
Jump to: navigation, search


Why Interfaces?

Because devs want their codes are

  • Maintainable
  • Extensible
  • Easily Testable

What Is Interface

Microsoft says

Interfaces describe a group of functions that can belong to any class or struct

Other Def

it's a contract with public set of members:

  • Properties
  • Methods
  • Events
  • Indexers

Interface is just a contract, No implementation. Based on abstract classes.

public abstract class AbstractRegularPolygon
{
  public int NumberOfSides{get; set;)
  public int SideLength{get; set;)
  public AbstractRegularPolygon{int sides, int length)
  {
    NumberOfSides = sides;
    SideLength = length;
  }
 public double GetPerimeter()
 {
   return NumberOfSides * SideLength;
 }
 public abstract double GetArea()
}
public class Triangle:AbstractRegularPolygon
{
  public Triangle(int Length):
   base(3, Length){}
  public override  double GetArea()
  {
    return SideLength * SideLength * Math.Sqrt(3) / 4;
  }
}    


public interface IRegularPolygon
{
  int NumberOfSides{get; set;}
  int SideLength{get; set;}
  double GetPerimeter();
  double GetArea();
}

Comparison between abstract classes and interfaces

  • abstract classes may contain implementation, interfaces are only declarations
  • a class can inherit from a single abstract class, but inherit from multiple interfaces
  • abstract classes has access modifiers like public private, but interfaces are always public and don't use access modifiers
  • abstract classes can have valid members like Fields, Properties, Constructors, Destructors, Methods, Events, Indexers, but interfaces are a bit more limited and can have Properties, Methods, Events, Indexers

Sample of Concrete and Interface diff

Concrete

List<Person> people;
people = peopleRepo.GetPeople();
foreach (var person in people)
   PersonListBox.Items.Add(person)

Interface

IEnumerable<Person> people;     // IEnumeralbe people -> Not strongly typed usage
people = peopleRepo.GetPeople();
foreach (var person in people)
   PersonListBox.Items.Add(person)