Interfaces are a fundamental concept in C# programming, providing a powerful tool for abstraction and polymorphism. They define a contract that classes can implement, enabling more flexible and maintainable code structures.
An interface in C# is a reference type that defines a set of abstract members. These members can include methods, properties, events, and indexers. Unlike classes, interfaces cannot contain implementation details.
To declare an interface, use the interface
keyword followed by the interface name. By convention, interface names start with an "I".
public interface IExample
{
void Method1();
string Property1 { get; set; }
event EventHandler Event1;
}
Classes implement interfaces using the :
symbol, followed by the interface name.
public class MyClass : IExample
{
public void Method1()
{
// Implementation
}
public string Property1 { get; set; }
public event EventHandler Event1;
}
While both interfaces and abstract classes provide abstraction, they have key differences:
Interface | Abstract Class |
---|---|
Can't contain implementation | Can contain implementation |
Supports multiple inheritance | Doesn't support multiple inheritance |
All members are public by default | Can have different access modifiers |
Here's an example demonstrating how interfaces enable polymorphism:
public interface IShape
{
double CalculateArea();
}
public class Circle : IShape
{
public double Radius { get; set; }
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
public class Rectangle : IShape
{
public double Width { get; set; }
public double Height { get; set; }
public double CalculateArea()
{
return Width * Height;
}
}
// Usage
IShape shape1 = new Circle { Radius = 5 };
IShape shape2 = new Rectangle { Width = 4, Height = 6 };
Console.WriteLine(shape1.CalculateArea()); // Output: 78.54
Console.WriteLine(shape2.CalculateArea()); // Output: 24
In this example, both Circle
and Rectangle
implement the IShape
interface, allowing them to be treated polymorphically.
Interfaces are a crucial feature in C# programming, offering a powerful way to design flexible and extensible software systems. By mastering interfaces, developers can create more modular, maintainable, and scalable code. They play a vital role in implementing design patterns and principles of object-oriented programming.
To further enhance your C# skills, explore related concepts such as polymorphism, inheritance, and generics.