Introduction
In object-oriented programming, interfaces play a crucial role in defining the contracts for classes. In C#, an interface is a blueprint that declares a set of methods and properties without providing their implementation. This allows different classes to implement the same interface, ensuring that they all provide the specified behaviors. Interfaces promote code reusability, flexibility, and maintainability, making them an essential concept for developers. This article delves into the basics of interfaces in C# and provides an example to illustrate their use.
Interface
An interface in C# is defined using the interface keyword. It can contain method signatures, properties, events, and indexers. Unlike classes, interfaces cannot contain any implementation code. When a class implements an interface, it must provide concrete implementations for all the members declared in the interface.
Implementing an Interface
Consider an example to understand how interfaces work in C#. Define an interface IVehicle with a couple of methods and properties, and then implement it in two different classes: Car and Bike.
using System;
public interface IVehicle
{
string Brand { get; set; }
int Speed { get; set; }
void Accelerate();
void Brake();
}
public class Car : IVehicle
{
public string Brand { get; set; }
public int Speed { get; set; }
public void Accelerate()
{
Speed += 10;
Console.WriteLine($"{Brand} car accelerates to {Speed} km/h.");
}
public void Brake()
{
Speed -= 10;
Console.WriteLine($"{Brand} car slows down to {Speed} km/h.");
}
}
public class Bike : IVehicle
{
public string Brand { get; set; }
public int Speed { get; set; }
public void Accelerate()
{
Speed += 5;
Console.WriteLine($"{Brand} bike accelerates to {Speed} km/h.");
}
public void Brake()
{
Speed -= 5;
Console.WriteLine($"{Brand} bike slows down to {Speed} km/h.");
}
}
public class Program
{
public static void Main()
{
IVehicle myCar = new Car { Brand = "Toyota", Speed = 0 };
IVehicle myBike = new Bike { Brand = "Honda", Speed = 0 };
myCar.Accelerate();
myCar.Brake();
myBike.Accelerate();
myBike.Brake();
}
}
Output
Conclusion
Interfaces in C# provide a powerful way to define contracts for classes, ensuring that they adhere to a specific set of behaviors. By using interfaces, developers can create flexible and maintainable code, allowing different classes to implement the same set of methods and properties. This example demonstrates how interfaces can be used to define common behaviors for different types of vehicles, promoting code reusability and consistency. Understanding and effectively utilizing interfaces is a fundamental skill for any C# developer, leading to more robust and scalable applications.