Interfaces
Introduction to Interfaces
An interface in .NET defines a contract that classes can implement. It specifies a set of methods, properties, events, or indexers that implementing classes must provide. Interfaces enable polymorphism and decouple the implementation from the interface definition.
Defining an Interface
In .NET, interfaces are declared using the interface
keyword. They contain method and property signatures but no implementation.
Example: Defining an Interface
public interface IShape {
void Draw();
double Area { get; }
}
Implementing Interfaces
Classes that implement an interface must provide implementations for all members defined in the interface.
Example: Implementing an Interface
public class Circle : IShape {
public void Draw() {
// Implement Draw method
}
public double Area {
get {
// Calculate area of circle
return Math.PI * Radius * Radius;
}
}
public double Radius { get; set; }
}
Using Interfaces for Polymorphism
Interfaces support polymorphism, allowing objects of different classes to be treated as instances of the same interface.
Example: Using Interfaces for Polymorphism
IShape shape = new Circle();
shape.Draw();
double area = shape.Area;
Interface Inheritance
Interfaces can inherit from other interfaces, enabling the creation of hierarchies of interfaces.
Example: Interface Inheritance
public interface IMovable {
void Move();
}
public interface IResizable : IMovable {
void Resize();
}
Conclusion
Interfaces in .NET provide a powerful mechanism for defining contracts that classes must adhere to. They facilitate code reusability, polymorphism, and separation of concerns, making applications more flexible and maintainable.