C# Interfaces
Overview
Interfaces define contracts that classes can implement. They specify what a class must do without specifying how it does it.
Basic Interface
csharp
public interface IDrawable
{
void Draw();
double GetArea();
}
public class Circle : IDrawable
{
public double Radius { get; set; }
public Circle(double radius) => Radius = radius;
public void Draw() => Console.WriteLine($"Drawing circle with radius {Radius}");
public double GetArea() => Math.PI * Radius * Radius;
}Multiple Interfaces
csharp
public interface IMovable
{
void Move(double x, double y);
}
public interface IResizable
{
void Resize(double factor);
}
public class AdvancedShape : IDrawable, IMovable, IResizable
{
public void Draw() => Console.WriteLine("Drawing shape");
public double GetArea() => 100; // Implementation
public void Move(double x, double y) => Console.WriteLine($"Moving to ({x}, {y})");
public void Resize(double factor) => Console.WriteLine($"Resizing by {factor}");
}Default Interface Methods (C# 8.0+)
csharp
public interface ILogger
{
void Log(string message) => Console.WriteLine($"Log: {message}");
void LogError(string error) => Console.WriteLine($"Error: {error}");
}Practical Usage
csharp
public class DrawingManager
{
public void DrawAll(List<IDrawable> shapes)
{
foreach (var shape in shapes)
{
shape.Draw();
}
}
}