Interfaces in C# are a fundamental part of the language's support for abstraction and polymorphism. They allow you to define contracts that classes or structs must implement, enabling flexible and loosely coupled designs. This document provides a thorough exploration of interfaces, including their syntax, purpose, advanced features, and practical use cases.
An interface is a reference type in C# that defines a set of method signatures, properties, events, or indexers without any implementation. It specifies what a class or struct should do but not how it does it.
By implementing an interface, a class or struct agrees to provide implementations for all members declared in the interface.
public interface IShape
{
double GetArea();
double GetPerimeter();
}
Here, IShape declares two methods that any implementing class must define.
public class Rectangle : IShape
{
public double Width { get; set; }
public double Height { get; set; }
public double GetArea()
{
return Width * Height;
}
public double GetPerimeter()
{
return 2 * (Width + Height);
}
}
Interfaces provide several important benefits:
Interfaces can declare several types of members, all of which are implicitly public and abstract (no implementation, unless using default interface methods - see below):
public interface INotifier
{
event EventHandler NotificationReceived;
string Status { get; set; }
void Notify(string message);
}
A class or struct can implement more than one interface, allowing a flexible composition of behaviors.
public interface IFlyable
{
void Fly();
}
public interface ISwimmable
{
void Swim();
}
public class Duck : IFlyable, ISwimmable
{
public void Fly()
{
Console.WriteLine("Flying");
}
public void Swim()
{
Console.WriteLine("Swimming");
}
}
When a class implements multiple interfaces that have members with the same signature, or when you want to hide interface methods from the public API, you can implement the interface explicitly.
public interface IFirst
{
void DoWork();
}
public interface ISecond
{
void DoWork();
}
public class Worker : IFirst, ISecond
{
void IFirst.DoWork()
{
Console.WriteLine("First DoWork");
}
void ISecond.DoWork()
{
Console.WriteLine("Second DoWork");
}
}
Usage:
Worker worker = new Worker(); ((IFirst)worker).DoWork(); // Output: First DoWork ((ISecond)worker).DoWork(); // Output: Second DoWork
Starting from C# 8.0, interfaces can provide default implementations for members. This allows interface authors to add new members without breaking existing implementations.
public interface ILogger
{
void Log(string message)
{
Console.WriteLine($"Log: {message}");
}
}
Classes implementing ILogger can override Log but arenβt required to.
public class ConsoleLogger : ILogger
{
// Uses default Log implementation
}
public class FileLogger : ILogger
{
public void Log(string message)
{
// Custom file logging logic
}
}
Interfaces can inherit from one or more other interfaces, enabling hierarchical contracts.
public interface IMovable
{
void Move();
}
public interface IAnimal : IMovable
{
void Eat();
}
public class Dog : IAnimal
{
public void Move()
{
Console.WriteLine("Dog moves");
}
public void Eat()
{
Console.WriteLine("Dog eats");
}
}
| Aspect | Interface | Abstract Class |
|---|---|---|
| Purpose | Defines a contract with no implementation (except default methods) | Defines a partial implementation |
| Multiple Inheritance | Supported (a class can implement multiple interfaces) | Not supported (only single inheritance) |
| Members | Methods, properties, events, indexers | Can contain fields, constructors, full method implementations |
| Access Modifiers | Members are implicitly public | Members can have access modifiers |
| Versioning | Default implementations from C# 8.0 allow better versioning | Can add new methods without breaking derived classes |
Variables of an interface type can reference any object that implements the interface, enabling polymorphism.
public interface IWorker
{
void Work();
}
public class Developer : IWorker
{
public void Work()
{
Console.WriteLine("Writing code");
}
}
public class Manager : IWorker
{
public void Work()
{
Console.WriteLine("Managing team");
}
}
IWorker worker = new Developer();
worker.Work(); // Output: Writing code
worker = new Manager();
worker.Work(); // Output: Managing team
One of the SOLID design principles states that no client should be forced to depend on methods it does not use. Interfaces enable this by breaking large interfaces into smaller, more specific ones.
public interface IPrinter
{
void Print();
}
public interface IScanner
{
void Scan();
}
public class MultiFunctionPrinter : IPrinter, IScanner
{
public void Print() { /* ... */ }
public void Scan() { /* ... */ }
}
public class SimplePrinter : IPrinter
{
public void Print() { /* ... */ }
}
Interfaces can be generic, allowing type parameters to specify flexible contracts.
public interface IRepository{ void Add(T item); T Get(int id); }
public class UserRepository : IRepository{ public void Add(User item) { /* ... */ } public User Get(int id) { /* ... */ return new User(); } }
Interfaces are widely used in DI frameworks to inject dependencies, enhancing testability and modularity.
// Define an interface
public interface IMessageService
{
void SendMessage(string message);
}
// Implement the interface
public class EmailService : IMessageService
{
public void SendMessage(string message)
{
Console.WriteLine("Sending email: " + message);
}
}
// Consumer class
public class Notification
{
private readonly IMessageService _messageService;
public Notification(IMessageService messageService)
{
_messageService = messageService;
}
public void Notify(string message)
{
_messageService.SendMessage(message);
}
}
Explicit interface implementation allows methods to be accessible only via interface references, hiding them from the public API of the class.
public interface ILogger
{
void Log(string message);
}
public class SilentLogger : ILogger
{
void ILogger.Log(string message)
{
// Does nothing (silently ignores logs)
}
}
SilentLogger logger = new SilentLogger();
// logger.Log("Hi"); // Error: not accessible
((ILogger)logger).Log("Hi"); // Works fine
public interface IShape
{
double GetArea();
double GetPerimeter()
{
return 0; // Default implementation returns zero
}
}
Interfaces have evolved significantly:
public interface IPaymentProcessor
{
bool ProcessPayment(decimal amount);
}
public class PaypalProcessor : IPaymentProcessor
{
public bool ProcessPayment(decimal amount)
{
Console.WriteLine("Processing PayPal payment");
return true;
}
}
public class StripeProcessor : IPaymentProcessor
{
public bool ProcessPayment(decimal amount)
{
Console.WriteLine("Processing Stripe payment");
return true;
}
}
public interface ILogger
{
void LogInfo(string message);
void LogError(string message);
}
public class ConsoleLogger : ILogger
{
public void LogInfo(string message) => Console.WriteLine($"INFO: {message}");
public void LogError(string message) => Console.WriteLine($"ERROR: {message}");
}
public class FileLogger : ILogger
{
public void LogInfo(string message) { /* write to file */ }
public void LogError(string message) { /* write to file */ }
}
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved