Utilizor
Contact Us

C# Interface

Define a contract that classes must implement.

C# Inteface

An interface is a completely "abstract class", which can only contain empty methods and properties (with no bodies).

interface IAnimal 
{
  void animalSound(); // interface method (does not have a body)
  void run(); // interface method (does not have a body)
}

It is considered good practice to start with the letter "I" at the beginning of an interface, as it makes it easier for yourself and others to remember that it is an interface and not a class.

By default, members of an interface are abstract and public.

To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class. To implement an interface, use the : symbol (just like with inheritance). The body of the interface method is provided by the "implement class". Note that you do not have to use the override keyword when implementing an interface.

Multiple Interfaces

C# does not support "multiple inheritance" (a class can only inherit from one base class). However, it can receive properties and methods from multiple interfaces.

To implement multiple interfaces, separate them with a comma:

class DemoClass : IFirstInterface, ISecondInterface 
{
  ...
}

Examples

Interface Implementation

Implementing an interface in a class.

using System;

interface IAnimal 
{
  void animalSound(); // interface method
}

class Pig : IAnimal 
{
  public void animalSound() 
  {
    Console.WriteLine("The pig says: wee wee");
  }
}

class Program 
{
  static void Main(string[] args) 
  {
    Pig myPig = new Pig(); 
    myPig.animalSound();
  }
}

Multiple Interfaces

Implementing multiple interfaces.

using System;

interface IFirst
{
  void myMethod();
}

interface ISecond
{
  void myOtherMethod();
}

class DemoClass : IFirst, ISecond
{
  public void myMethod()
  {
    Console.WriteLine("First Interface");
  }
  public void myOtherMethod()
  {
    Console.WriteLine("Second Interface");
  }
}

class Program
{
  static void Main()
  {
    DemoClass myObj = new DemoClass();
    myObj.myMethod();
    myObj.myOtherMethod();
  }
}