C# Delegates and Interfaces
1. What is a delegate in C#?
Definition: A delegate is a type-safe reference to a method. It allows you to store a method reference in a variable and execute that method through the delegate.
A delegate can reference any method that matches its parameter types and return type.
Example Program
// Step 1: Declare delegate
public delegate void MessageDelegate(string message);
public class Program
{
// Step 2: Create method
public static void DisplayMessage(string message)
{
Console.WriteLine(message);
}
public static void Main()
{
// Step 3: Assign method to delegate
MessageDelegate msg = DisplayMessage;
// Step 4: Invoke delegate
msg("Hello C#");
}
}
Output:
Hello C#
Explanation
-
MessageDelegatedeclares a delegate accepting astringand returningvoid. -
DisplayMessage()has the same method signature. -
msg = DisplayMessageassigns the method reference to the delegate. -
msg("Hello C#")invokes the referenced method.
Flow Diagram
Delegate Declaration
|
v
MessageDelegate
|
v
Assign DisplayMessage()
|
v
msg("Hello C#")
|
v
DisplayMessage("Hello C#")
|
v
Output: Hello C#
Types of Delegates
|
Type |
Description |
|---|---|
|
Single-cast |
References one method |
|
Multicast |
References multiple methods |
|
|
Built-in delegate with no return value |
|
|
Built-in delegate that returns a value |
|
|
Built-in delegate returning |
Key Points
-
A delegate is a type-safe method reference.
-
Delegates support both static and instance methods.
-
Delegates can reference multiple methods using
+=. -
Delegates are commonly used for callbacks, events, and LINQ.
-
Action,Func, andPredicate<T>are predefined delegate types. -
Delegates help reduce tight coupling between the caller and the method implementation.
2. What is the difference between delegates and interfaces?
Definition:
-
Delegate: Defines a method signature and holds references to compatible methods.
-
Interface: Defines a contract that classes or structs must implement.
Example Program
Using Delegate:
public delegate void NotificationDelegate(string message);
public class Program
{
public static void SendEmail(string message)
{
Console.WriteLine("Email: " + message);
}
public static void Main()
{
NotificationDelegate notify = SendEmail;
notify("Payment Successful");
}
}
Using Interface:
public interface INotification
{
void Send(string message);
}
public class EmailNotification : INotification
{
public void Send(string message)
{
Console.WriteLine("Email: " + message);
}
}
Usage:
INotification notification = new EmailNotification();
notification.Send("Payment Successful");
Output for both:
Email: Payment Successful
Explanation
Delegate approach:
-
NotificationDelegatespecifies the method signature. -
SendEmail()is assigned to the delegate. -
The delegate invokes the method directly.
Interface approach:
-
INotificationdefines theSend()contract. -
EmailNotificationimplements that contract. -
The method is called through an interface reference.
Flow Diagram
DELEGATE
--------
Caller
|
v
NotificationDelegate
|
v
SendEmail()
|
v
Email Sent
INTERFACE
---------
Caller
|
v
INotification
|
v
EmailNotification
|
v
Send()
|
v
Email Sent
Differences
|
Feature |
Delegate |
Interface |
|---|---|---|
|
Purpose |
Reference and invoke methods |
Define contracts |
|
Represents |
Method signature |
Collection of members |
|
Implementation |
Compatible method |
Implementing class/struct |
|
Multiple methods |
Supports multicast invocation |
Can define multiple members |
|
Invocation |
Through delegate variable |
Through interface reference |
|
Common usage |
Events, callbacks, LINQ |
DI, services, repositories |
|
Flexibility |
Change referenced method at runtime |
Change implementation object at runtime |
When should you use each?
Use a delegate when:
-
You need to pass a method as a parameter.
-
You need a callback after an operation.
-
You are implementing event handlers.
-
You need simple, interchangeable behavior.
Use an interface when:
-
You need multiple related methods or properties.
-
You want to define a service contract.
-
You are implementing Dependency Injection.
-
You need interchangeable implementations of business functionality.
Real-world ASP.NET Core Example
For a payment application:
public interface IPaymentService
{
void ProcessPayment(decimal amount);
}
Use an interface because payment processing represents a business service contract.
For a callback:
Action<string> onCompleted =
message => Console.WriteLine(message);
onCompleted("Payment Completed");
Use a delegate because you only need to execute a callback method.
Key Points
-
Delegates represent behavior through method references.
-
Interfaces define contracts for types.
-
Delegates are ideal for callbacks and events.
-
Interfaces are ideal for service abstraction and Dependency Injection.
-
Both support loose coupling, but they solve different design problems.
-
An interface is generally preferable when multiple related operations belong to the same abstraction.
Quick Interview Revision
|
Question |
Short Answer |
|---|---|
|
What is a delegate? |
A type-safe reference to a method |
|
Can delegates call multiple methods? |
Yes, using multicast delegates |
|
Can delegates reference instance methods? |
Yes |
|
What is an interface? |
A contract implemented by classes or structs |
|
Delegate vs interface? |
Delegate represents method behavior; interface represents a type contract |
|
Which is used for callbacks? |
Delegate |
|
Which is used for Dependency Injection? |
Usually interface |
|
Can both support loose coupling? |
Yes |
Interview takeaway: Use delegates when you want to pass or invoke methods dynamically. Use interfaces when you want to define contracts for interchangeable classes or services.