C# Interfaces
An interface defines a contract of methods and properties that implementing classes must provide, without specifying how they work. Interfaces are declared with the `interface` keyword and conventionally start with a capital I, like IShape.
Unlike classes, a class can implement multiple interfaces in C#, making interfaces a powerful way to achieve flexible, multiple-inheritance-like designs.
interface IName {
void Method();
}
class MyClass : IName {
public void Method() { }
}Defining and implementing interfaces
An interface lists method signatures without implementations. A class implements an interface using the colon syntax and must provide implementations for every member.
Interfaces vs abstract classes
A class can implement many interfaces but inherit from only one base class. Interfaces define a pure contract, while abstract classes can also share implementation and state.
using System;
interface IShape {
double Area();
}
class Rectangle : IShape {
public double Width, Height;
public Rectangle(double w, double h) { Width = w; Height = h; }
public double Area() { return Width * Height; }
}
class Program {
static void Main() {
IShape shape = new Rectangle(3, 4);
Console.WriteLine(shape.Area());
}
}12Rectangle implements the IShape interface by providing its own Area() method.
using System;
interface IFlyable { void Fly(); }
interface ISwimmable { void Swim(); }
class Duck : IFlyable, ISwimmable {
public void Fly() { Console.WriteLine("Flying"); }
public void Swim() { Console.WriteLine("Swimming"); }
}
class Program {
static void Main() {
Duck d = new Duck();
d.Fly();
d.Swim();
}
}Flying
SwimmingDuck implements two interfaces, gaining both behaviors at once.
Key points
- An interface defines a contract of members without implementation.
- A class can implement multiple interfaces, unlike class inheritance.
- Implementing classes must provide code for every interface member.
- Interface names conventionally start with a capital I.
