What is interface in c# explain with example


In C#, an interface is a contract that defines a set of methods, properties, events, or indexers that a class must implement. It provides a way to achieve multiple inheritances and helps in achieving abstraction. Here's a simple example:


// Define an interface named IShape
public interface IShape
{
    double CalculateArea(); // Method signature, to be implemented by classes
}

// Implement the interface in a class
public class Circle : IShape
{
    public double Radius { get; set; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    // Implement the method from the interface
    public double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}

// Another class implementing the same interface
public class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }

    // Implement the method from the interface
    public double CalculateArea()
    {
        return Width * Height;
    }
}

class Program
{
    static void Main()
    {
        // Create instances of the classes
        Circle circle = new Circle(5);
        Rectangle rectangle = new Rectangle(4, 6);

        // Use the CalculateArea method through the interface
        Console.WriteLine($"Circle Area: {circle.CalculateArea()}");
        Console.WriteLine($"Rectangle Area: {rectangle.CalculateArea()}");
    }
}


In this example, `IShape` is the interface with a method `CalculateArea()`. Both the `Circle` and `Rectangle` classes implement this interface, providing their own implementation of the `CalculateArea` method. The `Main` method demonstrates how you can use objects of these classes through the common interface.

Comments

Popular posts from this blog

Authentication Filters in Web APIs in dotnet core

Custom filters of asp.net core api

What is Middleware in asp.net core