๐ŸŽ“ A1Learner
๐Ÿ”

C# Interfaces

An interface is a list of methods that a class promises to provide. The interface names each method and gives it no body.

Dog implements IAnimal

IAnimal names a Sound method with no body. Dog provides the body.

using System;

interface IAnimal
{
    void Sound();
}

class Dog : IAnimal
{
    public void Sound()
    {
        Console.WriteLine("Woof");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dog dog = new Dog();
        dog.Sound();
    }
}

One class, two interfaces

Dog implements IAnimal and IPet here. It provides a body for the method of each interface.

using System;

interface IAnimal
{
    void Sound();
}

interface IPet
{
    void Play();
}

class Dog : IAnimal, IPet
{
    public void Sound()
    {
        Console.WriteLine("Woof");
    }

    public void Play()
    {
        Console.WriteLine("The dog fetches the ball");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dog dog = new Dog();
        dog.Sound();
        dog.Play();
    }
}

An interface-typed variable

The variable has the type IAnimal here. It holds a Dog object and calls Sound.

using System;

interface IAnimal
{
    void Sound();
}

class Dog : IAnimal
{
    public void Sound()
    {
        Console.WriteLine("Woof");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IAnimal myAnimal = new Dog();
        myAnimal.Sound();
    }
}

Example

using System;

interface IDrawable
{
    void Draw();
}

class Circle : IDrawable
{
    public void Draw()
    {
        Console.WriteLine("Drawing a circle");
    }
}

class Square : IDrawable
{
    public void Draw()
    {
        Console.WriteLine("Drawing a square");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IDrawable first = new Circle();
        IDrawable second = new Square();
        first.Draw();
        second.Draw();
    }
}

Key points

  • The interface keyword starts an interface definition.
  • A class implements an interface by naming it after a colon.
  • An implementing class writes a public body for each named method.
  • A class can implement more than one interface.
  • A variable of an interface type can hold an implementing object.

In this example, IDrawable names a Draw method with no body. Circle provides a Draw body that prints the circle line. Square provides a Draw body that prints the square line. Both variables hold their objects through the interface type.

Note

A class inherits one base class but can implement many interfaces.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What does a method inside an interface contain?