C# Delegates

In C#, a delegate represents a reference type variable that points to a method, providing functionality akin to a function pointer in C and C++. Delegates present a secure, type-safe, and object-oriented mechanism, enabling the passing of methods as arguments, their assignment to variables, and dynamic invocation during program execution. This feature is extensively utilized in C# for event handling implementations.

The code snippet below illustrates a placeholder with a background styled using a linear gradient. It has a border radius of 12 pixels, padding of 40 pixels, and a margin of 20 pixels at the top and bottom. The content is centered within the placeholder. The placeholder also includes an icon with a font size of 3 REM units and some text with a font size of 1 REM unit.

In C#, a delegate has the ability to encapsulate both a static method and an instance method. Essentially, a delegate declaration creates a class that inherits from the System.Delegate class internally.

Declaration of Delegates

A delegate type is defined by using the delegate keyword followed by a method signature. When a delegate is declared, it points to and executes methods that match its return type and parameter list specified in the delegate declaration.

Syntax:

It has the following syntax:

Example

[modifier] delegate [return_type] [delegate_name] ([parameter_list]);

In this syntax,

  • modifier: It represents an access modifier that defines the delegate's visibility.
  • delegate: It represents a keyword that defines the delegate.
  • return_type: It represents the value type that is returned by the methods.
  • delegate_name: It is used to represent the delegate name.
  • parameter_list: It represents the parameter list that the method must be assigned to the delegate.
  • Instantiating a delegate

Once a delegate is defined within C#, it can be initialized by linking it with a method (using the "new" keyword) that aligns with its signature. This functionality enables us to invoke the associated method indirectly via the delegate instance.

Syntax:

It has the following syntax.

Example

[delegate_name] [instance_name] = new [delegate_name](calling_method_name);

C# Delegate Example

Let's consider an example to demonstrate the delegate concept in C#.

Example

Example

using System;

namespace C# Tutorial

{

    // defining a delegate

    public delegate void MyDel(string msg);

    class Program

    {

        public static void Point(string msg)

        {

            Console.WriteLine("Hello, " + msg);

        }

        static void Main(string[] args)

        {

            MyDel del = new MyDel(Point);

            del("Albert"); // calling the delegate

        }

    }

}

Output:

Output

Hello, Albert

Explanation:

In this instance, a delegate named MyDel is defined, encompassing the Point function that accepts a string parameter. Subsequently, the Point function adheres to this structure and displays the specified message. Within the primary method, the delegate is initialized with the Point function and then invokes the Point function to display the result.

Passing Delegates as a Parameter

In C#, we have the capability to supply a delegate as an argument to a method. This enables the invocation of the method pointed to by the delegate. By employing this approach, we can establish a versatile and reusable method that has the ability to receive various functions as inputs.

C# Passing Delegates as a Parameter Example

Let's consider an instance to demonstrate the delegate utilizing a parameter passed by reference in C#.

Example

Example

using System;

namespace C# Tutorial

{

    // defining the delegate

    public delegate void My_Del(string msg);

    class Program

    {

        

        public static void Say(string n)

        {

            Console.WriteLine("Welcome to C# ProgrammingTech, " + n);

        }

        public static void GreetUser(My_Del del, string u)

        {

            del(u);

        }

        static void Main(string[] args)

        {

            // Assign the method 

            My_Del my_del = Say;

            // Passing the delegate 

            GreetUser(my_del, "David"); 

        }	

    }

}

Output:

Output

Welcome to C# ProgrammingTech, David

Explanation:

In this instance, a delegate named My_Del is defined, which includes the Say function. The Say function corresponds to this delegate and displays a message. The GreetUser function receives a delegate and a string as arguments. Within the primary function, an instance of the delegate is instantiated and linked to the Say function. Subsequently, this delegate, along with the name "David," is provided to GreetUser. Ultimately, the Say function is invoked to output the message.

Multicast Delegate

In C#, a multicast delegate is a unique delegate type capable of storing references to multiple methods simultaneously. Upon invocation, the delegate triggers the execution of all linked methods consecutively. This feature is beneficial for invoking numerous functions through a single delegate. It is essential that all methods share identical signatures and return types.

C# Multicast Delegate Example

Let's consider a scenario to demonstrate the multicast delegate feature in C#.

Example

Example

using System;

namespace C# Tutorial

{

    // defining a delegate

    public delegate void My_Del(string msg);

    class Program

    {

        // First method

        public static void SayHello(string n)

        {

            Console.WriteLine("Welcome, " + n);

        }

        // Second method

        public static void Say(string n)

        {

            Console.WriteLine("Welcome to C# ProgrammingTech, " + n);

        }

        static void Main(string[] args)

        {

            // Create delegate instances

            My_Del d1 = Say;

            My_Del d2 = Say;

            // Combining delegates

            My_Del multi = d1 + d2;

            // Call the multicast delegate

            multi("David");

        }

    }

}dc

Output:

Output

Welcome to C# ProgrammingTech, David

Welcome to C# ProgrammingTech, David

Explanation:

In this instance, a delegate named My_Del is defined with a string parameter and two functions, SayHello and Say. Within the primary function, two instances d1 and d2 are instantiated which point to the Say method. Subsequently, the multicast delegate instances are employed to display the resulting output.

Generic Delegate

A universal delegate in C# is a delegate type that includes a type parameter, allowing it to operate with various data types. Creating a delegate without specifying the data type enhances code flexibility and reusability.

C# Generic Delegate Example

Let's consider a scenario to demonstrate the generic delegate in C#.

Example

Example

using System;

namespace C# Tutorial

{

    // Generic delegate

    public delegate T MyDel<T>(T value);

    class Program

    {	

        public static int Sq(int num)

        {

            return num * num;

        }

        public static string Greet(string name)

        {

            return "Welcome, " + name;

        }

        static void Main(string[] args)

        {

            // create a delegate instance 

            MyDel<int> Del = Sq; 

            Console.WriteLine("The square of a number is " + Del(5));

            // Delegate instance for string

            MyDel<string> dd = Greet; 

            Console.WriteLine(dd("Alice")); 

        }

    }

}

Output:

Output

The square of a number is 25

Welcome, Alice

Explanation:

In this instance, we've utilized the generic delegate MyDel<T> with a single parameter of type T that yields the same type as output. Within the primary function, we instantiate two delegates: one for integers to compute the square of a number via the Sq function, and another for strings to welcome a user with a message returned from the Greet function.

Build-in Delegate

The subsequent table illustrates the predetermined generic delegates provided in C#.

Delegate Description Example
Action_PRESERVE13__ It defines a method that takes parameters but returns void. Action_PRESERVE14__ greet = name => Console.WriteLine("Hello, " +name);
Func_PRESERVE15__ It represents a method that takes a parameter with a return type. Func_PRESERVE16__ add = (m, n) => m + n;
Predicate_PRESERVE17__ It represents a method that takes a parameter and returns a Boolean type. Predicate_PRESERVE18__ isEven = x => x % 2 == 0;

Important Points of Delegate:

There are several important points of C# delegates. Some of them are as follows.

  • Delegates provide a convenient way to encapsulate methods and treat them as objects.
  • It is defined in the System namespace as a class type.
  • They are mainly used to implement callback methods and event handling.
  • Delegate can be used to invoke anonymous methods.
  • Delegates can call more than one method at the same time by linking them together.
  • Conclusion

In summary, a delegate is a data type that stores a pointer to a function. This enables functions to be transferred as arguments, stored in variables, and called dynamically during program execution. Delegates are extensively utilized for managing events, making the code more modular, reusable, and easier to maintain.

C# Delegate FAQs

1) What is a delegate in C#?

A delegate in C# serves as a type-safe reference to a method, functioning as a secure and object-oriented alternative to function pointers. It is a class type located within the System namespace.

2) Why use a delegate in C#?

In C#, a delegate serves as a data type that stores a pointer to a method, enhancing code flexibility and facilitating modifications. This feature enables the delayed execution of the method.

3) What is a generic delegate in C#?

A standard delegate in C# is a delegate type that includes a type parameter, allowing it to operate with diverse data types. This feature permits the creation of delegates without specifying a fixed data type, enhancing code flexibility and reusability.

4) How do we invoke a delegate in C#?

In C#, triggering a delegate involves using its name followed by parentheses, mirroring the process of invoking a standard method. If the delegate includes parameters, they are supplied as arguments.

Example: myDelegate; or myDelegate(10);

5) Define multicast delegate in C#?

A multicast delegate is a unique form of delegate capable of storing multiple methods concurrently. Upon invocation, the delegate executes each method sequentially, allowing for the execution of numerous functions through a single delegate. It is essential that all methods possess identical signatures for proper functionality.

6) Is it possible to utilize lambda expressions with delegates in C#?

Yes, lambda expressions can be utilized with delegates in the C# programming language.

Input Required

This code uses input(). Please provide values below: