Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now

C# Delegates and Events

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:02:00

Delegates:

Delegates in C# are reference types that hold references to methods, enabling method invocation indirectly. They are often used for implementing callbacks, event handling, and encapsulating method references.

Singlecast Delegate:

A singlecast delegate points to a single method and can invoke that method directly. It's the simplest form of a delegate.

Example:

// Declare a singlecast delegate
delegate void MyDelegate(string message);
// Assign a method to the delegate
MyDelegate singlecastDelegate = Console.WriteLine;
// Invoke the delegate
singlecastDelegate("Hello, world!");

Multicast Delegate:

A multicast delegate can hold references to multiple methods and invoke them all when invoked. It's useful for implementing event handling scenarios.

Example:

// Declare a multicast delegate
delegate void MultiDelegate(string message);
// Assign multiple methods to the delegate
MultiDelegate multicastDelegate = Console.WriteLine;
multicastDelegate += Console.WriteLine;
// Invoke the delegate (both methods are called)
multicastDelegate("Hello, world!");

Generic Delegate:

Generic delegates like Func and Action were introduced in C# 3.0, allowing you to create delegates without explicitly defining custom delegate types.

Example:

// Using generic delegates (Func and Action)
Action<string> printMessage = Console.WriteLine;
Func<int, int, int> add = (a, b) => a + b;
printMessage("Hello, world!");
int result = add(5, 3);
Console.WriteLine("Result: " + result);

Events:

Events in C# are a higher-level concept built on delegates. They allow for the implementation of the observer pattern, enabling one or more objects to respond to an event when it occurs. Events ensure a safer and more controlled way of handling callbacks.

Example:

public class Example
{
    // Declare an event
    public event Action<string> MyEvent;
    // Method to trigger the event
    public void RaiseEvent(string message)
    {
        MyEvent?.Invoke(message);
    }
}
static void Main(string[] args)
{
    Example example = new Example();
    // Subscribe to the event
    example.MyEvent += message => Console.WriteLine("Received: " + message);
    // Trigger the event
    example.RaiseEvent("Hello, world!");
}
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this