(C# Language) Interfaces

An interface is a collection of related functionality. An audio player is an audio player only if it implements the ability to play, pause, stop, etc., We can say that the functions play, pause, stop are together an interface called IAudioControls. An interface is a set of functions grouped together under the interface keyword. An interface cannot contain instance data members - they can, however, contain static data members - but that's an entirely different thing because static members are tied to a class or interface, not to a specific object. In this tutorial we examine various aspects of interfaces from C# perspective.
(Rev. 07-Nov-2022)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

What can an interface contain?

We shall create an interface that contains the most commonly added members.

An interface is written with the interface keyword. The name of an interface usually starts with the letter I in uppercase. If a class implements an interface then it must provide a definition for each and every function that has been declared without a body. The default access modifier in an interface is public. But you can use others as per need.

This interface declares a function without giving its body. C# compiler treats this function as public, so we do not have to specifically mark it as public. The function doesn't define its body. It is, therefore, compulsory for an implementing class to provide the body for this function.


// this interface contains commonly used members 
// but it can contain a lot more 

interface IMyInterface
{
  // implementation MUST be 
  // provided by implementing classes 
  void Myfunction();
    
  // default implementation of functions 
  // but classes can provide own implementation also 
  String MyName() => "IMyInterface";

  String MyName2() 
  { 
    return "IMyInterface"; 
  }

  // an interface can contain properties as well. 
  // implementing classes must implement getter, setters 
  // this is the property signature 
  String Version { get;  }

  // instance fields aren't permitted in interfaces 
  // it is an important difference with an abstract class 
  // int mData; 

  // static data members possible 
  private static float PI = 3.14f;

  // static functions possible 
  static float PrintPI2() => PI * PI;

  // C# 11 static virtuals also possible 
  // Used for: operator overloading 
  // an implementing class MUST provide  
  // a definition for this function 
  static virtual int gx();
}

An interface can provide a default implementation of a function. For example we have a function called MyName that returns a string "IMyInterface". The implementation is now optional because a default body exists. We have used a shortcut to define this function because it is a single line function. The return statement is not required for expression bodied functions. If this function is confusing then we have next added another function MyName2 that provides the body in the well-known traditional syntax.

An interface can contain properties as well. It can provide default implementations. If no implementation is provided, then the compiler treats it as a signature declaration, which makes it compulsory for an implementing class to provide the body.

We have added a property called Version. The interface hasn't provided the body for the getter function. So it is now compulsory for the implementing class to provide its body.

An interface cannot contain instance data members. We shall get a compiler error if we try to add a member called int mData. This is an important difference between an abstract class and an interface.

An interface can contain static data members and static functions, and, therefore, static constructors as well. It's not that strange as it might appear because static members are tied to the interface, and not to the objects of the implementing classes.

Starting from C# 11 version it is possible to add virtual static members. Such members are used for scenarios that require operator overloading.

Video Explanation (see it happen!)

Please watch the following youtube video:

C# interface vs Abstract classes

There is so much common between an interface and an abstract class that makes it imperative to learn the differences between the two.

  1. An interface describes the capabilities of the implementing class. But an abstract base class is a building base for similar types of classes.
  2. An interface cannot contain instance data members but an abstract class can contain instance data members.

Implementing an Interface

Let's next implement the interface that we have written.

Here's the class that implements the interface. Notice that the syntax for implementation requires us to use a colon followed by the name of the interface.

First we have completed the definition for Myfunction.

After that we have provided the getter for the Version property. Everything else is optional so we can leave them un-implemented.


// source code is in the attached downloads 

class MyClass : IMyInterface
{

  // implementation of function 
  public void Myfunction()
  {
    Console.WriteLine("MyClass - Myfunction called!");
  }

  // implementation of property 
  public string Version { get => "1.0"; }
  
}

Finally, let's have a look at the main function also. The source code has been attached as the downloads to this tutorial. So I will show the main function here.


static void Main()
{
  // create an object of the class 
  var obj = new MyClass();

  // get the interface 
  IMyInterface iface = obj as IMyInterface;

  // call a function 
  iface.Myfunction();

  // read a property 
  String ver = iface.Version;

  Console.WriteLine($"Version {ver}");

  // static members with dot syntax 
  IMyInterface.PrintPI2();
}

First we have an instance of the class.

Next we obtain the interface by casting. We could have obtained it at the time of creating the instance also IMyInterface iface = new CMyClass();.

The implemented function Myfunction is called next.

Similarly the property Version has been read. It is displayed on the console as well.

Finally, the static member function PrintPI2 has been called by using the name of the interface because the static member belongs to the interface.

What else an interface contain?

An interface can contain various types of items. Now I will list all the various types of members that an iterface can contain:

  1. static and non-static: Methods, Properties, Array Indexers [] and Events.
  2. Constants, Operators, Static constructors, and deeper nestings

You will have to refer msdn documentation for a further study of these details.

Explicit Interface Implementation

Suppose we have two interfaces containing functions of the same name, same signature as you are seeing here. Both the interfaces happen to contain void Play() function of the same name and signature.


// two interfaces containing a function 
// of same signature 

interface IAudioPlayer
{
  void Play();
}

interface IVideoPlayer
{
  void Play();
}

Also suppose we have a class that has to implement both the interfaces. The question is how to resolve this ambiguity.

We can give two implementations of void Play() by explicitly implementing the two interfaces. The syntax is to use the name of the respective interface. We can implement the Play function of IAudioPlayer by writing it as IAudioPlayer.Play, and similarly we can implement IVideoPlayer.Play.


// a class that implements both interfaces 

class MyClass : IAudioPlayer, IVideoPlayer
{
  // explicit implementation 
  void IVideoPlayer.Play()
  {
  }

  // explicit implementation 
  void IAudioPlayer.Play()
  {
  }
}


This Blog Post/Article "(C# Language) Interfaces" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.