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

Implementing Interfaces

In this page:

  1. Implementing Interfaces

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());
    }
}
🔒

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.