Master C# Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Delegates & Events

Delegates and Events are important features of C# used to implement flexible, reusable, and event-driven programming. Delegates provide a way to reference methods, while events are used to notify other parts of an application when something happens.

Simple Definition: A delegate is a type-safe reference to a method. An event is a mechanism used to notify subscribers when an action occurs.

What is a Delegate?

A delegate is a type that can hold a reference to a method. The method assigned to a delegate must have a compatible signature with the delegate.

Delegates are commonly used for callbacks, event handling, notifications, and passing methods as parameters.

Delegate Syntax

C#
delegate returnType DelegateName(parameters);

Simple Delegate Example

C#
delegate void MessageDelegate();

class Program
{
    static void ShowMessage()
    {
        Console.WriteLine("Welcome to CIIT Training Institute 👨‍🏫❤️...!");
    }

    static void Main()
    {
        MessageDelegate message = ShowMessage;

        message();
    }
}
Output
Welcome to CIIT Training Institute 👨‍🏫❤️...!

Delegate with Parameters

A delegate can also reference a method that accepts parameters.

C#
delegate void CalculateDelegate(int a, int b);

class Program
{
    static void Add(int a, int b)
    {
        Console.WriteLine(a + b);
    }

    static void Main()
    {
        CalculateDelegate calculate = Add;

        calculate(10, 20);
    }
}
Output
30

Delegate with Return Value

A delegate can reference a method that returns a value.

C#
delegate int CalculateDelegate(int a, int b);

class Program
{
    static int Add(int a, int b)
    {
        return a + b;
    }

    static void Main()
    {
        CalculateDelegate calculate = Add;

        int result = calculate(10, 20);

        Console.WriteLine(result);
    }
}
Output
30

Multicast Delegate

A multicast delegate can reference more than one method. The methods are executed in the order in which they are added.

C#
delegate void MessageDelegate();

class Program
{
    static void FirstMessage()
    {
        Console.WriteLine("First Message");
    }

    static void SecondMessage()
    {
        Console.WriteLine("Second Message");
    }

    static void Main()
    {
        MessageDelegate message = FirstMessage;

        message += SecondMessage;

        message();
    }
}
Output
First Message
Second Message

Action Delegate

Action is a built-in generic delegate that can reference a method returning void.

C#
Action message = () =>
{
    Console.WriteLine("Hello from Action");
};

message();
Output
Hello from Action

Func Delegate

Func is a built-in generic delegate used when a method returns a value.

C#
Func<int, int, int> add =
    (a, b) => a + b;

int result = add(10, 20);

Console.WriteLine(result);
Output
30

Events in C#

An event is used to notify other parts of an application when a particular action occurs.

Real-World Examples: Button clicks, order placement, payment completion, registration completion, and notification systems.

Creating an Event

Events are commonly declared using a delegate type. Other objects can subscribe to the event and receive notifications.

C#
class Order
{
    public event Action OrderPlaced;

    public void PlaceOrder()
    {
        Console.WriteLine("Order placed.");

        OrderPlaced?.Invoke();
    }
}

class Program
{
    static void Main()
    {
        Order order = new Order();

        order.OrderPlaced += SendNotification;

        order.PlaceOrder();
    }

    static void SendNotification()
    {
        Console.WriteLine("Notification sent.");
    }
}
Output
Order placed.
Notification sent.

Event Subscription

The += operator is used to subscribe a method to an event.

C#
order.OrderPlaced += SendNotification;

The method will be called when the event is raised.

Removing an Event Handler

The -= operator is used to unsubscribe a method from an event.

C#
order.OrderPlaced -= SendNotification;

Event with Custom Event Arguments

Events can pass additional information using EventArgs-derived classes.

C#
class OrderEventArgs : EventArgs
{
    public int OrderId { get; set; }
}

class Order
{
    public event EventHandler<OrderEventArgs> OrderPlaced;

    public void PlaceOrder(int orderId)
    {
        Console.WriteLine("Order placed.");

        OrderPlaced?.Invoke(
            this,
            new OrderEventArgs
            {
                OrderId = orderId
            });
    }
}

class Program
{
    static void Main()
    {
        Order order = new Order();

        order.OrderPlaced += HandleOrderPlaced;

        order.PlaceOrder(101);
    }

    static void HandleOrderPlaced(
        object sender,
        OrderEventArgs e)
    {
        Console.WriteLine(
            "Order ID: " + e.OrderId);
    }
}
Output
Order placed.
Order ID: 101

Delegate vs Event

Feature Delegate Event
Purpose References methods Provides notifications
Invocation Can be invoked by its holder Normally raised by its declaring type
Common Usage Callbacks Event-driven programming
Example Action, Func Button click, order placed

Example ❤️👨‍🏫

Consider an e-commerce application. When a customer places an order, multiple actions may need to happen, such as sending a notification, updating inventory, and creating an invoice.

C#
class OrderService
{
    public event Action OrderPlaced;

    public void PlaceOrder()
    {
        Console.WriteLine("Order created.");

        OrderPlaced?.Invoke();
    }
}

class Program
{
    static void Main()
    {
        OrderService service = new OrderService();

        service.OrderPlaced += SendEmail;
        service.OrderPlaced += UpdateInventory;

        service.PlaceOrder();
    }

    static void SendEmail()
    {
        Console.WriteLine("Email notification sent.");
    }

    static void UpdateInventory()
    {
        Console.WriteLine("Inventory updated.");
    }
}
Output
Order created.
Email notification sent.
Inventory updated.
CIIT Practical Point: Delegates and Events are important in .NET applications for callbacks, notifications, event-driven programming, UI events, messaging systems, and loosely coupled application components.

Common Mistakes

  • Using a delegate with an incompatible method signature.
  • Forgetting to subscribe to an event.
  • Forgetting to unsubscribe event handlers when required.
  • Raising an event without checking whether it has subscribers.
  • Using delegates when a simpler method call would be enough.
  • Confusing the purpose of delegates and events.

Interview Questions

1. What is a delegate in C#?

A delegate is a type-safe reference to a method.

2. What is a multicast delegate?

A multicast delegate can reference multiple methods and invoke them together.

3. What is an event?

An event is a mechanism used to notify subscribers when something happens in an application.

4. What is the difference between delegate and event?

A delegate is primarily used to reference and invoke methods, while an event provides controlled notification to subscribers.

5. What are Action and Func?

Action represents a delegate that returns void, while Func represents a delegate that returns a value.

6. What is the use of += with events?

The += operator subscribes a method to an event.

Summary

Delegates provide a type-safe way to reference methods and are commonly used for callbacks and flexible method execution.

You also learned about multicast delegates, built-in Action and Func delegates, and how multiple methods can be associated with a delegate.

Events provide a controlled way to notify subscribers when an action occurs. They are widely used in event-driven applications and notification systems.

Understanding Delegates and Events is important for developing flexible and maintainable .NET and ASP.NET Core applications.

Practice Questions

  1. Create a delegate that references a simple method.
  2. Create a delegate with two integer parameters.
  3. Create a delegate that returns an integer value.
  4. Create a multicast delegate with two methods.
  5. Demonstrate the Action delegate.
  6. Demonstrate the Func delegate.
  7. Create an event for an order placement operation.
  8. Subscribe a method to an event.
  9. Unsubscribe a method from an event.
  10. Create an event using EventHandler and custom EventArgs.
  11. Explain the difference between delegates and events.
  12. Explain real-world applications of delegates and events.