What is Interface With Example Code

In C#, an interface defines a contract that classes can implement.
It specifies a set of members methods, properties, events, or indexers that implementing
classes must provide. Interfaces allow for polymorphism,
enabling objects of different classes to be treated uniformly if they implement the same interface.




using System;
 
// Define an interface named IShape
public interface IShape
{
    // Method signatures
    double GetArea();
    double GetPerimeter();
}
 
 
// Define a class named Circle that implements the IShape interface
public class Circle : IShape
{
 
    // Fields
    private double radius;
 
    // Constructor
    public Circle(double radius)
    {
        this.radius = radius;
    }
 
    // Implementing methods from the IShape interface
    public double GetArea()
    {
        return Math.PI * radius * radius;
    }
 
    public double GetPerimeter()
    {
        return 2 * Math.PI * radius;
    }
 
}
 
 
 
// Define another class named Rectangle that implements the IShape interface
public class Rectangle : IShape
{
 
    // Fields
    private double width;
    private double height;
 
    // Constructor
    public Rectangle(double width, double height)
    {
        this.width = width;
        this.height = height;
    }
 
    // Implementing methods from the IShape interface
    public double GetArea()
    {
        return width * height;
    }
 
    public double GetPerimeter()
    {
        return 2 * (width + height);
    }
 
}
 
class Program
{
    static void Main(string[] args)
    {
        // Create objects of Circle and Rectangle
        Circle circle = new Circle(5);
 
        Rectangle rectangle = new Rectangle(4, 6);
        // Display information about the shapes
 
        Console.WriteLine("Circle:");
 
        Console.WriteLine($"Area: {circle.GetArea()}, Perimeter: {circle.GetPerimeter()}");
 
        Console.WriteLine("\nRectangle:");
 
        Console.WriteLine($"Area: {rectangle.GetArea()}, Perimeter: {rectangle.GetPerimeter()}");
 
    }
}