Interface (C#)
An interface is a contract that lists method and property signatures a class must implement, without providing the code. It defines what a type can do, not how it does it.
C#
Interface names conventionally start with a capital I, like IComparable or IEnumerable. A class implements an interface with a colon, then must provide a body for every member.
Interfaces let unrelated classes be used interchangeably as long as they fulfill the contract, which is the basis of flexible, loosely-coupled designs. A class can implement many interfaces at once.
Syntax
interface IName { ReturnType Method(); }Examples
C#
interface IShape
{
double Area();
}
class Square : IShape
{
public double Side;
public double Area() => Side * Side;
}
IShape s = new Square { Side = 4 };
Console.WriteLine(s.Area());Output:
16