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.
  • A brief intro of abstract classes

    Abstract classes are created for derivation purposes only. They consists of default method and attribute implementations which would be available to the data types/classes deriving from the abstract class.
    Few interesting points about abstract classes:

  • It’s not possible to instantiate an object of an abstract class, except in the context of instantiating a class that derives from it.
  • An abstract class can have both abstract and non-abstract members. The abstract members define what an object deriving from the abstract class should contain, but they don’t include the implementation. The implementation is provided by the deriving classes
  • Because abstract members need to be overridden, they are automatically virtual and cannot be declared so explicitly.
  • Abstract members cannot be private as derived classes would not be able to see them.
  • Abstract classes are a way to enable polymorphism. The base class specifies the method signature and the derived classes provide the various specific implementations.
  • HTH!

    Follow

    Get every new post delivered to your Inbox.