Let's explore interfaces in C# through clear examples and explanations that both beginners and advanced programmers can understand.
An interface is like a contract that defines what a class must be able to do, without specifying how it should do it. Think of it as a list of promises that a class makes to implement certain methods or properties.
<aside> Key Points about Interfaces:
</aside>
// Interface definition
public interface IWorker
{
// Method declaration (no implementation)
void DoWork();
// Property declaration
string JobTitle { get; set; }
}
// Class implementing the interface
public class Employee : IWorker
{
// Must implement all interface members
public string JobTitle { get; set; }
public void DoWork()
{
// Implementation goes here
Console.WriteLine("Doing work...");
}
}
Let's break down the previous example with detailed comments:
/// <summary>
/// Base class representing a human being
/// </summary>
public class Human
{
// Property to store the person's name
public string Name { get; set; }
// Constructor to initialize the name
public Human(string name)
{
Name = name;
}
}
/// <summary>
/// Interface defining electrical work capabilities
/// </summary>
public interface IElectrician
{
void ChangeLightBulb(); // Method that must be implemented
}
/// <summary>
/// Interface defining plumbing capabilities
/// </summary>
public interface IPlumber
{
void UnplugDrain(); // Method that must be implemented
}
/// <summary>
/// HandyPerson class that inherits from Human and implements both interfaces
/// This demonstrates multiple interface implementation
/// </summary>
public class HandyPerson : Human, IElectrician, IPlumber
{
// Constructor calls the base (Human) constructor
public HandyPerson(string name) : base(name) { }
// Implementation of IElectrician interface
public void ChangeLightBulb()
{
Console.WriteLine($"{Name} is changing the light bulb professionally");
}
// Implementation of IPlumber interface
public void UnplugDrain()
{
Console.WriteLine($"{Name} is unplugging the drain professionally");
}
}
In C#, it's conventional to prefix interface names with 'I':