Why we use interfaces C# with Example



Why we use interfaces C# with Example

An interface is a definition of a contract between the user of the interface and the class that implement it. One way 
to think of an interface is as a declaration that an object can perform certain functions. 
Let's say that we define an interface IShape to represent different type of shapes, we expect a shape to have an 
area, so we will define a method to force the interface implementations to return their area : 
public interface IShape 
{ 
double ComputeArea(); 
} 
Let's that we have the following two shapes : a Rectangle and a Circle 
public class Rectangle : IShape 
{ 
private double length; 
private double width; 
public Rectangle(double length, double width) 
{ 
this.length = length; 
 

this.width = width; 
} 
public double ComputeArea() 
{ 
return length * width; 
} 
} 
public class Circle : IShape 
{ 
private double radius; 
public Circle(double radius) 
{ 
this.radius = radius; 
} 
public double ComputeArea() 
{ 
return Math.Pow(radius, 2.0) * Math.PI; 
} 
} 
Each one of them have its own definition of its area, but both of them are shapes. So it's only logical to see them as 
IShape in our program : 
private static void Main(string[] args) 
{ 
var shapes = new List() { new Rectangle(5, 10), new Circle(5) }; 
ComputeArea(shapes); 
Console.ReadKey(); 
} 
private static void ComputeArea(IEnumerable shapes) 
{ 
foreach (shape in shapes) 
{ 
Console.WriteLine("Area: {0:N}, shape.ComputeArea()); 
} 
} 
// Output: 
// Area : 50.00 
// Area : 78.54 

0 Comment's

Comment Form

Submit Comment