Why we use interfaces

suggest change

An interface is a definition of a contract between the user of the interface and the class that implement it. One way to think of an interface is as a declaration that an object can perform certain functions.

Let’s say that we define an interface IShape to represent different type of shapes, we expect a shape to have an area, so we will define a method to force the interface implementations to return their area :

public interface IShape
{
    double ComputeArea();
}

Let’s that we have the following two shapes : a Rectangle and a Circle

public class Rectangle : IShape
{
    private double length;
    private double width;

    public Rectangle(double length, double width)
    {
        this.length = length;
        this.width = width;
    }

    public double ComputeArea()
    {
        return length * width;
    }
}

public class Circle : IShape
{
    private double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    public double ComputeArea()
    {
        return Math.Pow(radius, 2.0) * Math.PI;
    }
}

Each one of them have its own definition of its area, but both of them are shapes. So it’s only logical to see them as IShape in our program :

private static void Main(string[] args)
{
    var shapes = new List<IShape>() { new Rectangle(5, 10), new Circle(5) };
    ComputeArea(shapes);

    Console.ReadKey();
}

private static void ComputeArea(IEnumerable<IShape> shapes) 
{
    foreach (shape in shapes)
    {
        Console.WriteLine("Area: {0:N}, shape.ComputeArea());
    }
}

// Output:
// Area : 50.00
// Area : 78.54

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Interfaces:
* Why we use interfaces

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
40 Interfaces
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script