← Back to C# Course | Chapter 8: Interfaces | Lesson 2 of 6

Implementing Interfaces

Implementing an interface means a class signs the promise list and then actually provides every action on it. It is like a job candidate showing they can do all the tasks required.

In this page:

  1. Implementing Interfaces
Syntax
csharp
class ClassName : IInterfaceName
{
    public ReturnType MethodName()   // every interface member needs a body
    {
    }
}

Implementing Interfaces

A class implements an interface by listing it after a colon and providing a concrete body for every member the interface declares. Failing to implement even one member is a compile error.

A variable typed as the interface can hold any object of a class that implements it.

Warning: Implementing only some of an interface's members will not compile — every member is required.

Example: Implementing Interfaces

markup
using System;

interface IShape
{
    double Area();
    double Perimeter();
}

class Square : IShape
{
    public double Side;
    public Square(double side) { Side = side; }

    public double Area() => Side * Side;
    public double Perimeter() => Side * 4;
}

class Program
{
    static void Main(string[] args)
    {
        IShape shape = new Square(5);
        Console.WriteLine(shape.Area());
        Console.WriteLine(shape.Perimeter());
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not implementing every member of the interface, which is a compile error.
  2. Implementing an interface method as non-public, which is not allowed for implicit implementations.
  3. Changing the signature slightly, so the method does not match the interface.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.