C# Interface class and its usage


 In C#, an interface is a fundamental concept that allows you to define a contract for classes. An interface defines a set of methods, properties, events, or indexers that a class must implement. It serves as a blueprint for a set of common behaviors that various classes can adhere to, providing a way to achieve abstraction and polymorphism. Here's how you define and use interfaces in C#:

Defining an Interface:

You define an interface using the interface keyword, and you can specify the methods, properties, events, or indexers that classes implementing the interface must provide. For example:

public interface IShape { double CalculateArea(); double CalculatePerimeter(); }

In this example, IShape is an interface with two methods, CalculateArea() and CalculatePerimeter(), which any class that implements IShape must implement.

Implementing an Interface:

To implement an interface in a class, you use the : interfaceName notation in the class declaration. For example:

public class Circle : IShape { public double Radius { get; set; } public Circle(double radius) { Radius = radius; } public double CalculateArea() { return Math.PI * Radius * Radius; } public double CalculatePerimeter() { return 2 * Math.PI * Radius; } }

The Circle class implements the IShape interface, providing concrete implementations for CalculateArea() and CalculatePerimeter().

Using Interfaces:

  1. Polymorphism: You can use interfaces to achieve polymorphism, where you can treat objects of different classes that implement the same interface in a uniform way. For example:
IShape shape = new Circle(5.0); double area = shape.CalculateArea(); double perimeter = shape.CalculatePerimeter();

In this case, you can work with shape as an IShape regardless of its actual implementation (a Circle in this case).

  1. Design by Contract: Interfaces define a contract that classes must adhere to. This is particularly useful when defining specifications for your classes or when working with third-party libraries that provide interfaces that you need to implement.

  2. Multiple Inheritance: C# supports multiple interface inheritance, allowing a class to implement multiple interfaces. This is a way to achieve a form of multiple inheritance while avoiding the complications of multiple inheritance of implementation.

public class Square : IShape, IDrawable { // Implement methods from IShape and IDrawable here }

Interfaces are a crucial part of object-oriented programming in C#. They help you create flexible, maintainable, and extensible code by defining clear contracts and enabling polymorphism. By adhering to these contracts, classes can ensure they provide specific behaviors and functionality, making it easier to work with and extend your codebase.

Post a Comment

Previous Post Next Post