What is a delegate and how to use it in C#
Join the DZone community and get the full member experience.
Join For FreeThere are many articles around the web that are explaining what C# delegates are, but not many of them (I couldn’t find any, actually) cover this topic for those who just start with the entire concept. So I will try explaining this a bit more in detail, but keeping things simple at the same time.
Delegates allow the developer to call a method indirectly, therefore, providing an additional extensibility layer that comes in handy at runtime. It is declared via the delegate keyword and it accepts functions passed as parameters. Also, delegates can have a return value, although this is not necessarily the case, depending on the function passed.
Let’s start with an example. Here is a sample delegate declaration:
public delegate void SampleDelegate (int valueA, int valueB);
The delegate by itself is not doing anything, unless a function is passed. By the structure of the delegate, we can see what function should be passed to it. First of all, it is going to be a function that will not have a return value (hence, the void keyword is used). The function that will be passed should also require two parameters, both integers. Consider it a placeholder for an unknown function, but with a defined structure.
Using the delegate is quite simple. For example, there are two functions that perform mathematical operations with two integers and display the results (note, that there is no return value):
public static void ShowAddition (int a, int b)
{
int c = a + b;
Debug.Print (c.ToString());
}
public static void ShowMultiplication (int a, int b)
{
int c = a * b;
Debug.Print (c.ToString());
}
In my application, I can reference these functions via my delegate:
SampleDelegate myRef = new SampleDelegate (ShowAddition);
myRef (10, 20);
The result displayed will be:
30
I can pass the second function the same way:
SampleDelegate myRef = new SampleDelegate (ShowMultiplication);
myRef (10, 20);
The result shown will be:
200
A delegate can contain multiple references. Applying the same two functions, I can add them both to the delegate:
SampleDelegate myRef = new SampleDelegate (ShowMultiplication);
myRef += ShowAddition;
myRef (10, 20);
The results displayed will be:
200
30
The functions will be executed in the order of addition to the delegate.
Now, a developer could ask – how exactly is this adding an extensibility layer? With the same code volume, someone could directly use function calls. I showed a very generic use of a delegate. But a delegate can also be a parameter for another function. With the code above still present, I am going to add an additional function. It doesn’t have a specific purpose, but rather shows the capabilities of a delegate passed:
public void TestFunction (int a, int b, string message, SampleDelegate del)
{
int c = a * b + a;
del(a, b);
Debug.Print(message + " " + c.ToString());
}
This function two integers as parameters as well as a string and an instance of SampleDelegate. The numbers are then being used to perform some calculations, also being used for the delegate instance. In a delegate, the parameters are specified according to its signature (the structure used when declaring the delegate). Then, a message is being shown in the Output window with the result of the calculations. Simple as that. Now, the interesting part is here – this function has no idea what del will do. It only knows that it should accept two parameters of type int. For example, I can use the above function like this:
TestFunction(10, 10, "Result for the calculations:", ShowMultiplication);
The developer can pass any function that is following the delegate “guidelines” as the parameter. At the same time, this does not limit the possible functionality of that specific function. To show an example, here is a function that can be passed and executed:
public void AnotherFunction(int a, int b)
{
MessageBox.Show(string.Format("The first number is {0} and the second is {1}", a.ToString(), b.ToString()));
Application.Exit();
}
As you see, the function displays both numbers in a MessageBox
and then exits the application, without displaying the message that
would go after it if it is passed to the main function, shown above.
Also, an important note that must be made is that with C# 4.0 now
available, optional parameters can be used with delegates as well.
Therefore, I can specify a default value for a parameter:
public delegate void SampleDelegate(int valueA, int valueB = 10);
It is also important to remember that with the default parameter set, even if the function you pass assigns a different value for the second parameter (or any parameter that is declared as optional), the new value will be ignored and the default is used.
The same does not apply to functions with optional parameters – if a delegate requires a parameter, it should be present and cannot be skipped, therefore even a function with an optional parameter cannot be used without that optional parameter if required by the delegate.
Opinions expressed by DZone contributors are their own.
Trending
-
Tech Hiring: Trends, Predictions, and Strategies for Success
-
SRE vs. DevOps
-
Deploying Smart Contract on Ethereum Blockchain
-
Strategies for Reducing Total Cost of Ownership (TCO) For Integration Solutions
Comments