Sobes.tech
Junior — Middle

Explain what an interface in C# is and what role it plays in programming.

sobes.tech AI

Answer from AI

In C#, an interface is a contract that defines a set of methods, properties, events, or indexers, but does not contain their implementation. A class or struct that implements the interface is required to provide a concrete implementation of all its members.

The role of an interface in programming:

  • Provides abstraction and separates the definition of behavior from its implementation.
  • Allows creating flexible and extensible architectures that support polymorphism.
  • Simplifies testing and component replacement, as code works with interfaces rather than specific classes.

Example of an interface and its implementation:

public interface ILogger
{
    void Log(string message);
}

public class ConsoleLogger : ILogger
{
    public void Log(string message)
    {
        Console.WriteLine(message);
    }
}

Here, ILogger sets the logging contract, and ConsoleLogger implements it by outputting messages to the console.

Explain what an interface in C# is and what role it… - sobes.tech