Sobes.tech
Junior — Middle

Can you explain the concept of an interface in programming and its purpose?

sobes.tech AI

Answer from AI

In programming, an interface is a contract that defines a set of methods and properties that a class must implement, but does not contain their implementation. In C#, interfaces are used to ensure abstraction and polymorphism, allowing different classes to have a common set of methods, which simplifies interaction between components.

For example, an IShape interface might contain a Draw() method. Classes Circle and Rectangle implement this interface, providing their own implementation of the Draw() method.

public interface IShape
{
    void Draw();
}

public class Circle : IShape
{
    public void Draw()
    {
        Console.WriteLine("Drawing a circle");
    }
}

public class Rectangle : IShape
{
    public void Draw()
    {
        Console.WriteLine("Drawing a rectangle");
    }
}

Purposes of interfaces:

  • To provide a standardized way of interaction between classes.
  • To enable the use of polymorphism.
  • To simplify testing and maintenance of code.
  • To promote loose coupling of components.