Object Oriented Programming and C#: Interfaces

Interfaces are a vital subject to explore within object oriented programming. An interface contains definitions for a group of related functionalities that a class or struct can implement. The interface essential defines the “what” of the contract of the classes that inherit the interface abide by. The classes perform the “how” part of the contract. The general syntax for defining interfaces is to use to “Interface” keyword and then begin the name of the interface with a capital “I”. Every class that inherits properties from the interface must contain whatever method is in the interface. The methods defined in an interface cannot have a definition, only the declaration of the method.

In the following section of code, an interface named “IDogCommands” is initialized. When a class attempts to inherit the interface, an error is given because the methods initialized within the interface are not used within the class.

codesnip

An important application of implementation of interfaces in C# comes from the fact that multiple inheritance is not supported. Another is inheriting with a struct, which does not support inheritance directly. An important note is that an interface never includes implementation, only empty methods that serve as a signature. The implementation is done in the classes themselves. Interfaces can contain methods, properties, events, indexers, or any combination of those four member types.

As shown below, interfaces can even inherit from other interfaces. However you cannot instantiate an interface directly.

codesnip

The distinguishing features between abstract classes and interfaces are that abstract classes do not allow multiple inheritance and can contain access modifiers and variables (interfaces cannot). Additionally, abstract classes can contain implementations of methods, which as discussed, interfaces cannot.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s