Sobes.tech
Junior — Middle

Can you give an example of where an interface is used in a project?

sobes.tech AI

Answer from AI

An interface in C# is used to define a contract that classes must implement. This allows for flexible architecture and the use of polymorphism.

Example: in a project, there is an interface ILogger for logging:

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

public class FileLogger : ILogger
{
    public void Log(string message)
    {
        // write message to a file
    }
}

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

In the code, you can use ILogger without tying it to a specific implementation, which simplifies replacing the logger and testing.