C# Interface
An interface in C# is a blueprint of a class that defines a set of methods and properties that a class can implement. In other words, an interface defines a contract that a class must adhere to. Interfaces provide a way to achieve polymorphism and abstraction in C#.
Declaring an Interface
To declare an interface, use the interface
keyword followed by the interface name and its members. Here is an example:
1public interface IShape 2{ 3 void Draw(); 4 double Area { get; } 5}
The IShape
interface defines two members, a method Draw()
and a read-only property Area
. Any class that implements this interface must provide an implementation for both of these members.
Implementing an Interface
To implement an interface, a class must include the interface's name in its declaration and provide an implementation for all the members defined in the interface. Here is an example:
1public class Circle : IShape 2{ 3 public double Radius { get; set; } 4 5 public void Draw() 6 { 7 Console.WriteLine("Drawing Circle"); 8 } 9 10 public double Area 11 { 12 get { return Math.PI * Radius * Radius; } 13 } 14}
In this example, the Circle
class implements the IShape
interface by providing an implementation for both the Draw()
method and the Area
property.
Implementing Multiple Interfaces
A C# class can implement multiple interfaces by including all the interface names separated by commas in its declaration. Here is an example:
1public interface IResizable 2{ 3 void Resize(double factor); 4} 5 6public class ResizableCircle : IShape, IResizable 7{ 8 public double Radius { get; set; } 9 10 public void Draw() 11 { 12 Console.WriteLine("Drawing Circle"); 13 } 14 15 public double Area 16 { 17 get { return Math.PI * Radius * Radius; } 18 } 19 20 public void Resize(double factor) 21 { 22 Radius *= factor; 23 } 24}
In this example, the ResizableCircle
class implements both the IShape
and IResizable
interfaces by providing an implementation for all the members defined in both interfaces.