C# / C# Delegates, Events, and Lambdas

Understanding Delegates in C#

Delegates are a powerful feature of C# that allow for flexibility and modularity in your programs. This tutorial will introduce you to the concept of delegates and how to use them.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers delegates, events, and lambda expressions for advanced programming in C#.

Understanding Delegates in C

1. Introduction

In this tutorial, we will explore delegates in C#, an essential feature that brings flexibility and modularity to your programs. By the end of this tutorial, you will understand what delegates are, how to declare and use them, and where they are applicable.

Prerequisites: Basic knowledge of C# programming. Familiarity with concepts like classes, methods, and events is beneficial.

2. Step-by-Step Guide

Delegates in C# are similar to function pointers in C or C++, but they are type-safe. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.

Declaring Delegates

To declare a delegate, you use the delegate keyword, followed by a function signature, and finally a delegate name. Here's a simple example:

public delegate int MyDelegate(string s);

In this example, MyDelegate is a delegate type that can encapsulate a method taking a string as a parameter and returning an int.

Using Delegates

Once a delegate type is declared, a delegate object can be created with the new keyword and be associated with a particular method. Here's an example:

public int StringLength(string s) 
{
    return s.Length;
}

MyDelegate del = new MyDelegate(StringLength);

In this example, the del delegate object is associated with the StringLength method. This means that invoking del will invoke StringLength.

3. Code Examples

Basic Delegate Usage

Below is a full example of declaring, instantiating, and using a delegate.

using System;

public delegate int MyDelegate(string s); // Declare a delegate

class Program
{
    public static int ShowStringLength(string s) // Method that matches delegate signature
    {
        return s.Length;
    }

    static void Main()
    {
        MyDelegate del = new MyDelegate(ShowStringLength); // Instantiate the delegate

        int result = del("Hello, world!"); // Invoke the delegate

        Console.WriteLine(result); // Outputs: 13
    }
}

The expected output of this program is 13, which is the length of the string "Hello, world!".

4. Summary

In this tutorial, we've learned about delegates in C#, including their declaration, instantiation, and usage. Delegates are a powerful tool in C#, allowing for runtime method invocation and serving as the foundation for events.

To continue learning about delegates, look into multicast delegates and generic delegates, which are more advanced topics. The official Microsoft documentation is a great place to start.

5. Practice Exercises

  1. Create a delegate CalculateDelegate that can encapsulate methods taking two integers and returning an integer. Use this delegate to create methods that implement addition, subtraction, and multiplication.
  2. Modify the above program to use anonymous methods with the delegate.

Solutions will be provided in the comments.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help