📋 Interface = Contract, Not Implementation
Different classes need same behavior. Interfaces define contracts. Multiple implementations. Dependency injection, loose coupling.
📝 Defining Interface
public interface IPaymentProcessor
{
bool ProcessPayment(decimal amount, string currency);
void RefundPayment(string transactionId);
PaymentStatus CheckStatus(string transactionId);
}
public class StripeProcessor : IPaymentProcessor
{
public bool ProcessPayment(decimal amount, string currency)
{
// Stripe implementation
return true;
}
public void RefundPayment(string transactionId) { }
public PaymentStatus CheckStatus(string transactionId) { }
}
public class PayPalProcessor : IPaymentProcessor
{
public bool ProcessPayment(decimal amount, string currency)
{
// PayPal implementation
return true;
}
public void RefundPayment(string transactionId) { }
public PaymentStatus CheckStatus(string transactionId) { }
}
🎯 Using Interfaces
// Dependency injection
public class OrderService
{
private readonly IPaymentProcessor _paymentProcessor;
public OrderService(IPaymentProcessor paymentProcessor)
{
_paymentProcessor = paymentProcessor;
}
public void ProcessOrder(Order order)
{
_paymentProcessor.ProcessPayment(order.Total, order.Currency);
}
}
// Dependency injection registration
builder.Services.AddScoped();
// Or
builder.Services.AddScoped();
// Multiple implementations
public interface ILogger
{
void Log(string message);
}
public class ConsoleLogger : ILogger { }
public class FileLogger : ILogger { }
public class DatabaseLogger : ILogger { }
💡 Best Practices
- Name interfaces with I prefix (ILogger, IRepository)
- Keep interfaces small (single responsibility)
- Use interfaces for dependency injection
- Interface Segregation Principle (ISP)
- Programming to interfaces, not implementations
“Switched payment providers. Interface made it easy. New provider implements same interface. Service unchanged. Interfaces enable loose coupling.”

