Interfaces

Interfaces in C# are another way of achieving polymorphism apart from inheritance (via abstract classes :) ). They create a contract which requires the classes implementing the interface to provide implementation of the methods defined in the interface.

  • An interface cannot have implementation and data (fields) within it. When an interface requires the derived class to have certain data, it uses a property rather than a field and the property does not contain any implementation as part of declaration.
  • Defining private or protected members in an interface would defeat the purpose of the interface contract, thus C# does not allow access modifiers on interface members and instead it automatically defines them as public.
  • A class can implement multiple interfaces.
  • When a class declares that it implements an interface, all members of the interface must be implemented. Even at least with the NotImplementedException, but from a compiler’s perspective it should provide an implementation.
  • An interface can never be instantiated and thus cannot even have constructors or finalizers. Interface instances are available only through types that implement them.
  • An interface cannot have static members as polymorphism won’t be of any value if there is no instance of the implementing type.
  • Methods within an interface cannot have abstract modifier as they are automatically abstract.
  • Follow

    Get every new post delivered to your Inbox.