C# Interview Question #19
What is an interface in C#?
OOP & Core C# Concepts Junior Beginner
Quick Interview Answer
An interface defines a contract that implementing types agree to provide.
Detailed Explanation
An interface defines a contract that implementing types agree to provide.
Interfaces are heavily used in ASP.NET Core for dependency injection, loose coupling, unit testing, mocking, Clean Architecture, and SOLID design.
Modern C# interfaces can also contain certain default implementations, but their primary role in application architecture remains defining capabilities and contracts.
Code Example
public interface IProductService
{
Task<List<Product>> GetAllAsync();
Task<Product?> GetByIdAsync(int id);
}
public class ProductService : IProductService
{
public Task<List<Product>> GetAllAsync()
=> Task.FromResult(new List<Product>());
public Task<Product?> GetByIdAsync(int id)
=> Task.FromResult<Product?>(null);
}
// ASP.NET Core DI registration:
// builder.Services.AddScoped<IProductService, ProductService>();