Interfaces in C# provide a way to define a contract that classes can implement. They allow you to define a set of methods and properties that a class must implement, without specifying how they are implemented. This helps in achieving abstraction and creating reusable code.
To define an interface in C#, you can use the interface
keyword followed by the interface name. Here’s an example:
public interface IShape
{
void Draw();
double CalculateArea();
}
In the above example, we define an interface named IShape
with two methods: Draw()
and CalculateArea()
. Any class that implements this interface must provide implementations for these methods.
To implement an interface in a class, you can use the : interfaceName
syntax. Here’s an example:
public class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a circle");
}
public double CalculateArea()
{
// Calculate area logic
}
}
In the above example, the Circle
class implements the IShape
interface by providing the implementations for the Draw()
and CalculateArea()
methods.
Interfaces can also be used to achieve multiple inheritance in C#. A class can implement multiple interfaces by separating them with commas. Here’s an example:
public interface IResizable
{
void Resize(int width, int height);
}
public class RectangularShape : IShape, IResizable
{
// Implementation of IShape and IResizable methods
}
In the above example, the RectangularShape
class implements both the IShape
and IResizable
interfaces.
Interfaces can be useful in scenarios where you want to define a common contract that multiple classes can adhere to. They enable you to write code that depends on the contract rather than a specific implementation, which promotes loose coupling and modularity.
In conclusion, interfaces play an important role in C# programming by allowing you to define contracts that classes must implement. They help in achieving abstraction, creating reusable code, and facilitating multiple inheritance.