What Are C# Delegates And How To Use Them

Share the Post

C# delegates are a type that represents references to methods with a specific function signature. In short, delegates are references to methods.

Single cast C# Delegates

Read Also: Solving the 8 puzzle problem using A* (star) algorithm

An instantiated delegate can be associated with any method that has a compatible signature and return type. One can then call the method through the delegate instance. C# Delegates are used to pass methods as arguments to other methods. In other words, delegates are methods that you can use as variables, like strings, integers, objects etc. 

C# delegates allow us to create robust and complex behaviours in our Unity scripts. A C# delegate can be thought of as a container of a function that can be can be passed around or used as a variable. Just like variables delegates can have variables assigned to them. And these values can be changed at runtime. The only difference is that while variables contain data, C# delegates contain functions.

Recall the following:

  • What is a function signature?
  • What are arguments to function?
  • What is pass by value and pass by reference?

Based on C# syntax we can create a delegate with the delegate keyword, followed by a return type and the signature of the methods that can be delegated to it. For example, we can declare a delegate method with no argument as:

public delegate void NoArgDelegate();

Or a delegate with one argument (for this example let’s use string):

public delegate void OneArgDelegate(string val);

Or a delegate with two arguments (for this example let’s use an integer as first argument and string as the second argument):

public delegate void TwoArgDelegate(int val, string key);

We will now create three functions with the same function signature as the above C# delegates.

We can now call the delegate as below.

Exercise 1

Create a Unity project (either 2d or 3d). Add an empty game object to the scene, add a new script component called Delegate1. Implement three functions with the same signature as the above three delegates. Call the delegates from Start.

Now answer the following questions:

  • What is the difference between myfunc1 and myfunc1_other variables?
  • What will happen when we call myfunc2 as myfunc2(10);
  • Can you briefly explain what is happening in the codes written?

Why Use C# Delegates?

Objects and variables can easily be sent as parameters into methods or constructor, however, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that’s when you’ll need delegates.

By defining a delegate, you are saying to the user of your class, “Please feel free to assign, any method that matches this signature, to the delegate and it will be called each time my delegate is called”, from Stackoverflow, Delegates are useful to offer to the user of your objects some ability to customize their behaviour. Most of the time, you can use other ways to achieve the same purpose. It is just one of the easiest way in some situations to get the thing done.

Typical use cases are events and observers. All the OnEventX delegate to the methods the user defines.

Multicast C# Delegates

C# Delegates can be chained together; for example, multiple methods can be called on a single event.

In the previous section, we discussed simple delegates that take reference with a single method. These are called Single cast delegates. There is another type of delegates that can take references to more than one function. These are called Multicast delegates. 

In this section, we will discuss Multicast delegates. A multicast delegate is a delegate that has references to more than one function. When we invoke a multicast delegate, all the functions that the delegate is pointing to, are invoked. The best part of Multicast delegates is that we can add or remove references of multiple methods with the same instance of delegate using (+) or (-) sign respectively. All methods referenced by the delegate will be invoked in one process will take place in the sequence of the operations.

Look at the example below:

Discuss and ponder:

  • Can you briefly explain what is happening in the codes written?
  • Implement the code in your Unity project and see the output.
  • Try and implement at least one more similar example with one argument.

If a delegate has a return type other than void and if that delegate is a multicast delegate, then only the value of the last invoked method is returned. 

Along the same lines, if the delegate has an out parameter, the value of the output parameter will be the value assigned by the last method.

Read Also: How to Generate Mazes Using Depth-First Algorithm

Exercise 2

Open the existing Unity Project. Add a cube as a new game object. Add a script called Multicast.cs to the cube game object. Implement two functions that take in duration (float value) as a parameter 

  • The first function transforms the position upwards by a certain value. 
  • The second function changes the colour of the object 

Handle input for Up Arrow key and when clicked invoke a delegate that triggers both the functions. You can refer to the source codes below (but you cannot copy and paste).

In the above code, we declare the delegate, create an instance of the delegate and declare a public variable for Renderer. We also created two functions that call respective coroutines to change the position and colour of the object.

In the above code, we implement the coroutines to interpolate movement and colour based on time duration.

Finally,  we assign the functions to the multicast delegate and we invoke the delegate when Up Arrow key is pressed.

C# Delegates Using Anonymous Methods

Anonymous Methods permit code blocks to be passed as parameters in place of a separately defined method.

Lambda expression is a function that doesn’t have a name. The only way to execute this function is to have a delegate pointing to the function. Lambda expressions are usually defined in the place where you need a delegate to a function with a given footprint. This is useful to make code less verbose and at the same time more descriptive and flexible.

Continuing exercise 1 we can now rewrite the delegates as lambda expressions.

Exercise 3

2 thoughts on “What Are C# Delegates And How To Use Them”

  1. Pingback: Solving the 8 puzzle problem using A* (star) algorithm - edusing

  2. Pingback: How to Generate Mazes Using Depth-First Algorithm - edusing

Leave a Reply

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