Understanding Delegates in C#

Delegates in C#

Understanding Delegates in C#

Delegates are a fundamental feature of C# that allow you to pass methods as arguments to other methods. They are type-safe function pointers, enabling dynamic method calls. Delegates are widely used in event handling and callback mechanisms.

Defining and Using Delegates

A delegate is defined using the delegate keyword. Here is a basic syntax:

delegate returnType DelegateName(parameters);

Example 1: Basic Delegate

Let's create a delegate that takes two integers and returns their sum.

using System; class Program { // Define a delegate public delegate int Operation(int x, int y); static void Main(string[] args) { // Method that matches the delegate signature int Add(int a, int b) => a + b; // Create an instance of the delegate Operation operation = Add; // Call the delegate int result = operation(10, 20); Console.WriteLine($"Sum: {result}"); } }

Multicast Delegates

Delegates can hold references to multiple methods. When the delegate is invoked, all methods in its invocation list are executed.

using System; class Program { public delegate void Notify(); static void Method1() => Console.WriteLine("Method1 called"); static void Method2() => Console.WriteLine("Method2 called"); static void Main(string[] args) { Notify notify = Method1; notify += Method2; // Invoke delegate notify(); } }

Example 2: Delegates with Lambda Expressions

Delegates can be used with anonymous methods or lambda expressions for conciseness.

using System; class Program { public delegate void Greet(string name); static void Main(string[] args) { // Using a lambda expression Greet greet = name => Console.WriteLine($"Hello, {name}!"); greet("John"); } }

Example 3: Delegate for Sorting

Delegates can be used to pass sorting logic to methods. For example:

using System; class Program { public delegate int Comparison(int x, int y); static int AscendingOrder(int a, int b) => a - b; static int DescendingOrder(int a, int b) => b - a; static void Sort(int[] array, Comparison comparison) { for (int i = 0; i < array.Length - 1; i++) { for (int j = i + 1; j < array.Length; j++) { if (comparison(array[i], array[j]) > 0) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } } } static void Main(string[] args) { int[] numbers = { 5, 3, 8, 1, 2 }; Console.WriteLine("Original array: " + string.Join(", ", numbers)); Sort(numbers, AscendingOrder); Console.WriteLine("Sorted in ascending order: " + string.Join(", ", numbers)); Sort(numbers, DescendingOrder); Console.WriteLine("Sorted in descending order: " + string.Join(", ", numbers)); } }

Example 4: Delegate with Predicate

Using a delegate to filter elements in a collection:

using System; using System.Collections.Generic; class Program { public delegate bool Filter(int number); static List FilterNumbers(List numbers, Filter filter) { List result = new List(); foreach (var number in numbers) { if (filter(number)) { result.Add(number); } } return result; } static void Main(string[] args) { List numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Filtering even numbers List evenNumbers = FilterNumbers(numbers, n => n % 2 == 0); Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers)); // Filtering odd numbers List oddNumbers = FilterNumbers(numbers, n => n % 2 != 0); Console.WriteLine("Odd numbers: " + string.Join(", ", oddNumbers)); } }

Real-World Use Case: Event Handling

Delegates are commonly used in event handling. For instance:

using System; class Program { public delegate void Notify(string message); public static void OnNotification(string message) { Console.WriteLine($"Notification received: {message}"); } static void Main(string[] args) { Notify notifier = OnNotification; notifier("You have a new message."); } }

Advantages of Delegates

  • Allows dynamic method invocation.
  • Enables callback functionality.
  • Supports event-driven programming.
In summary, delegates in C# provide a powerful way to work with methods dynamically. They form the backbone of events and callbacks, making them indispensable in modern C# programming.

This Content Sponsored by Buymote Shopping app

BuyMote E-Shopping Application is One of the Online Shopping App

Now Available on Play Store & App Store (Buymote E-Shopping)

Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8

Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication
      

Post a Comment

0 Comments