Due to popular demand, we are back with yet another country capital quiz. See if you can answer all the…
A delegate is a type that represents references to methods with a specific function signature.
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. 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. Delegates allow us to create robust and complex behaviours in our Unity scripts. A 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, delegates contain functions.
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 mystr);
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 argc, string argv);
We will now create three functions with the same function signature as the above delegates.
We can now call the delegate as below.
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?
Microsoft introduced Anonymous Methods in C# 2.0. An anonymous method is an inline code that can be used wherever a delegate type is expected.
Delegates abstract and encapsulate a method. This is by far the most important use of delegates. It helps us to define an abstract reference which can point to methods and functions. The same abstract delegate can be later used to point to that type of functions and methods.
I write and publish quizzes, short stories, math puzzles, about blogging, and lifestyle. Follow Faramira e-magazine on Twitter and like us on Facebook to get the latest. Subscribe to our magazine in Flipboard (Faramira).