What is an Interface?
An interface is a contract: a list of members a class promises to provide. It says what can be done, not how.
Simple example: A wall socket is an interface. Any plug that fits can use it: a lamp, a phone charger or a fan. The socket does not care what the device is, only that it fits.
csharp
interface IPaymentMethod
{
string Name { get; }
bool Pay(decimal amount);
}
class CreditCard : IPaymentMethod
{
public string Name => "Credit Card";
public bool Pay(decimal amount)
{
Console.WriteLine($"Charged {amount:C} to card");
return true;
}
}
class PayPal : IPaymentMethod
{
public string Name => "PayPal";
public bool Pay(decimal amount)
{
Console.WriteLine($"Sent {amount:C} via PayPal");
return true;
}
}
Program to the Interface
csharp
class Checkout
{
public void Complete(IPaymentMethod method, decimal total)
{
if (method.Pay(total))
Console.WriteLine($"Paid with {method.Name}");
}
}
var checkout = new Checkout();
checkout.Complete(new CreditCard(), 49.99m);
checkout.Complete(new PayPal(), 19.50m);
Checkout works with any payment method, even ones that do not exist yet. This is the heart of flexible design.
Naming and Rules
- Interface names start with I:
IPaymentMethod
- A class can implement many interfaces:
class A : IFirst, ISecond
- Interface members are public by default
- You cannot create an object of an interface, only of a class that implements it
Built-In Interfaces You Will Use
| Interface | Purpose |
IDisposable | Release resources (using statement) |
IComparable<T> | Define the natural order for sorting |
IEnumerable<T> | Make something work in foreach and LINQ |
IEquatable<T> | Value equality |
csharp
class Employee(string name, decimal salary) : IComparable<Employee>
{
public string Name { get; } = name;
public decimal Salary { get; } = salary;
public int CompareTo(Employee? other) => Salary.CompareTo(other?.Salary);
}
var list = new List<Employee> { new("A", 300), new("B", 100), new("C", 200) };
list.Sort(); // by salary: B, C, A
Default Interface Methods
csharp
interface ILogger
{
void Log(string message);
void LogError(string message) => Log("ERROR: " + message); // default code
}
Why Interfaces Matter for Testing
When a class depends on IEmailSender instead of a real SmtpEmailSender, you can give it a fake sender in a unit test. We use this idea heavily in ASP.NET Core with dependency injection.
Conclusion
Interfaces define contracts. Depend on interfaces instead of concrete classes and your code becomes flexible, replaceable and easy to test.
Quick Summary: interface = contract. A class can implement many. Depend on the interface.