Appearance
Interfaces
Interfaces define a contract that classes must follow, specifying a set of methods and properties that implementing classes must provide. They enable loose coupling and help create more maintainable and flexible code.
Defining Interfaces
An interface declaration creates a contract that defines what members a class must implement. This establishes a common set of functionality across different classes.
csharp
public interface IShape
{
double GetArea();
double GetPerimeter();
}
Implementing Interfaces
Classes that implement an interface must provide concrete implementations for all members defined in the interface. This ensures consistency across different implementations.
csharp
public class Circle : IShape
{
public double Radius { get; set; }
public double GetArea()
{
return Math.PI * Radius * Radius;
}
public double GetPerimeter()
{
return 2 * Math.PI * Radius;
}
}
Multiple Interface Implementation
C# supports implementing multiple interfaces, allowing classes to fulfill multiple contracts. This provides flexibility in designing class hierarchies and behavior.
csharp
public interface IDrawable
{
void Draw();
}
public class Circle : IShape, IDrawable
{
// IShape implementation
public double GetArea() => Math.PI * Radius * Radius;
public double GetPerimeter() => 2 * Math.PI * Radius;
// IDrawable implementation
public void Draw()
{
Console.WriteLine("Drawing circle");
}
}