Example of delegate in C#

This example show you how to use delegate in C#.
A delegate in C# is similar to a function pointer in C or C++ but unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.
[1]

You can pass your Method to another method or class during runtime.
You can use “delegate” keyword to declare a “Type”.
Then use the declared “Type” like you use a type (e.g String, DateTime etc) in any method parameter.

Step 1
Declare a delegate same signature like the method you will pass in using the following format

public delegate void (param…)

e.g String getName();
e.g void setName(String s);

Step 2
Use the declared delegate “CustomCallableMethod” like a type in any method parameter (or variable declaration)

Step 3
Implement a method with the same signature

Step 4
Pass in the method like a parameter
Observe that homeNow is actually a static method declared in step 3

Step 5
Call the method according to the signature you have declared in step 1

If everything runs fine. You will see the Output

Hello Just
I am coming home now
Hello Example
I am leaving home now

Summary
Use of delegate is really handy when you do not know the method you need to call but only the signature of the method.
With delegate, you can avoid importing unwanted class into your code and pass the method in as parameter during runtime.
Have Fun!

Reference
1. https://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">