C# Delegates overview with examples

Mohammad Zubair 0
csharp delegates

Delegates are similar to C++ function pointers, but delegates are fully object-oriented, and unlike C++ pointers to member functions, delegates encapsulate both an object instance and a method. Delegates have the following properties:

  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Methods don’t have to match the delegate type exactly. For more information, see Using Variance in Delegates.
  • Lambda expressions are a more concise way of writing inline code blocks. Lambda expressions (in certain contexts) are compiled to delegate types. For more information about lambda expressions, see Lambda expressions.

Simple Example: 

using System;

// Define a delegate named MathOperationDelegate
delegate int MathOperationDelegate(int a, int b);

class Program
{
// Method that matches the signature of MathOperationDelegate
static int Add(int a, int b)
{
return a + b;
}

// Another method that matches the signature of MathOperationDelegate
static int Subtract(int a, int b)
{
return a - b;
}

static void Main(string[] args)
{
// Create delegate instances pointing to methods
MathOperationDelegate operation1 = Add;
MathOperationDelegate operation2 = Subtract;

// Use delegate instances to perform operations
int result1 = operation1(5, 3); // This will call Add(5, 3)
int result2 = operation2(5, 3); // This will call Subtract(5, 3)

Console.WriteLine("Result of addition: " + result1); // Output: 8
Console.WriteLine("Result of subtraction: " + result2); // Output: 2
}
}

In this example:

  • We define a delegate named MathOperationDelegate which represents a method that takes two integers as parameters and returns an integer.
  • We have two methods, Add and Subtract, which match the signature of the delegate (int(int, int)).
  • In the Main method, we create delegate instances operation1 and operation2, each pointing to a different method.
  • We then invoke these delegate instances with appropriate arguments, and they call the respective methods (Add or Subtract) as per their assignments.
  • This demonstrates how delegates can be used to encapsulate methods and pass them around as parameters or assign them to variables.

 


Mohammad Zubair

I'm Mohammad Zubair, a passionate software engineer working in the dynamic world of IT. Currently, I'm proud to be a part of HawarIT, a thriving Dutch-Bangladeshi joint venture company, where I contribute my expertise and enthusiasm to the field of software engineering.

Leave a Reply

Your email address will not be published. Required fields are marked *