22/08/2020
-> Working with Delegates
In essence, a delegate holds a reference to a method and also to the target object on which the method should be called. A delegate in C # is similar to function pointers of C++, but C # delegates are type safe. You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the "delegate" keyword. You can declare a delegate that can appear on its own or even nested inside a class.
There are three steps in using delegates. These include: declaration, instantiation, and invocation.
The signature of a delegate looks like this:
Why new remote work policies attract hackers
delegate result-type identifier ([parameters])
The following statement shows how you can declare a delegate.
public delegate void MyDelegate(string text);
As you can see in the above statement, the delegate name is "MyDelegate" can it has a return type of "void" and it accepts a string object as argument. This implies that the delegate MyDelegate can point to a method that has identical signature. This is just a declaration though -- you should always instantiate a delegate before you can use it. The statement given next shows how you can instantiate the delegate declared above.
MyDelegate d = new MyDelegate(ShowText);
Once you have declared and instantiated the delegate, you can invoke the method that the delegate points to easily.
d("Hello World...");
Here, d is the delegate instance
You can also invoke the method that the delegate instance points to using the Invoke() method on the delegate instance as shown below.
d.Invoke("Hello World...");
If you have a method that accepts two numbers and you want to add them and return the sum of the two numbers, you can use a delegate to store the return value of the method as shown in the code snippet given below.
int result = d(12, 15);
Here's the complete code listing for your refer