Interfaces define a contract that classes can implement. They allow for a flexible approach by specifying a set of methods or properties that the implementing classes must provide. While interfaces are similar to classes as a reference type that can include declarations of methods, properties, events, and more, they differ in that they do not contain any implementation details. Essentially, interfaces specify what a class should accomplish, but not the manner in which it should be achieved.
public interface IBook
{
string Title { get; set; }
string Author { get; set; }
int NumPages { get; set; }
}
public class Novel : IBook
{
public string Title { get; set; }
public string Author { get; set; }
public int NumPages { get; set; }
public Novel(string title, string author, int numPages)
{
Title = title;
Author = author;
NumPages = numPages;
}
public void DisplayInfo()
{
Console.WriteLine($"Title: {Title}, Author: {Author}, Pages: {NumPages}");
}
}
class Program
{
static void Main(string[] args)
{
IBook myBook = new Novel("1984", "George Orwell", 328);
myBook.DisplayInfo();
}
}
In this example, myBook is a type of IBook, but it holds a reference to a Novel object. This demonstrates how interfaces allow for flexible code that can work with any class implementing the interface. This example promotes loose coupling and makes the code more adaptable to changes, as any other class implementing IBook can be used interchangeably. In the business/real world, interfaces allow you to easily switch between implementations, such as swapping databases or logging frameworks, without changing the consuming code. Interfaces lead to more maintainable and scalable software designs.