Purpose
The purpose of this tutorial is to show a few different ways with which a delegate can be used under .Net Core 6+. It may also apply to earlier releases but I just have not had the time to find out myself.
Commonly delegates are thought of as a type that references a method like:
// Example Generic Delegate with Lambda
int ingress = 0; Func<int, int> method = ingress => ingress * 2;
Console.WriteLine(method(2)); //4
// Example Generic Delegate with Lambda
int ingress = 0; int egress = 0; public void noReturnData(int data) { egress = data; }
Action<int> method = ingress => noReturnData(ingress);
method(3); Console.WriteLine(egress); //3
However, a delegate method can also be passed to another method as an argument. This allows methods to communicate between each other, sort of like delegates in the real world. Here's what I mean:
public class WorkingClass {
// Define method which will be updated as each step of work is completed.
public void WorkProgress(int lastStepCompleted) {
Console.WriteLine(lastStepCompleted);
}
// Declare method as a delegate that will be used like a parameter.
// In this case, to monitor each work step completed.
public delegate void CallBack(int stepCompleted);
// Pass the delegate like a parameter to this method.
public void PerformWork(CallBack workStepCompleted) {
// Each time work is done (an iteration is completed), send update that a work step has been done.
for (int step = 1; step <= 5; step++) { workStepCompleted(step); }
}
// Start the work, until it is done.
public void Worker() {
PerformWork(WorkProgress);
// Work has now been completed.
Console.WriteLine("Work Done.");
}
}
The output will look like this:
1
2
3
4
5
Work Done.
Note: In this example, if you are having an issue getting public void Worker() to run, you could take the method body and place it in a method that you can execute. You may need to do something like updating the body to resolve the class such as:
WorkingClass myWorker = new WorkingClass();
myWorker.PerformWork(myWorker.WorkProgress);
// Work has now been completed.
Console.WriteLine("Work Done.");