What is delegate any way?
remember the topic called pointer to function in C/C++ you used to hate? well it’s back again !, but this time Microsoft made a good job making this easier and more safe and secure.
back in dark ages function pointers used to be defined as variable which points to address of a function, part of the fact that in C/C++ you had to manage memory your self it was kind of dangerous when you work with pointers in general, any way that is all changed in .net , now Delegates (reference to functions) are defined as
Type safe object which points to an execution of a method
so how you define a delegate to point to a method ?
consider this method:
public static void sum(int left, int right) { Console.WriteLine(left + right); }
in order to define a delegate which points to this function you do these steps :
- Clear Method Implementation.
- Clear static keyword.
- add the keyword “delegate” after method scope “public”.
- Add ; at the end.
- change sum to delegate name, (i will call it mydelegate).
public delegate void MyDelegate(int left, int right);
Congratulation you just declared your first delegate!, any way you have to remember that to define a delegate you have to provide 3 pieces of information of the method the delegate will point to:
- return type “in this example it’s void”.
- delegate name “Mydelegate”.
- Parameters “(int left, int right)”.
Now, what really happened behind the scene when you did that?
By declaring Mydelegate you just defined a delegate class type which inherits from “System.MultiCastDelegate”, which in turns provide you with the ability to register multi-methods to your delegate and provide you with a list of all the methods registered to your delegate!, in order to register a method to your delegate you have to create an object of your delegate and pass method name as a parameter to the constructor:
MyDelegate del = new MyDelegate(sum);
Now to call the method by referencing the delegate you do the following:
del(2, 3);
now if you want to register one more methods lets say this method:
public static void Multiplay(int left, int right) { Console.WriteLine(left * right); }
You register it as follows:
del += Multiplay;
Notice here we used a feature called Method Group Conversion which allows you to assign a method directly to a delegate for registering it. I would like to stress something in here which is when you register a Method to a delegate you actually registering the execution of that method, that way if you registered a method 3 times that means the execution of that methods is going to happen 3 times, this is because every time you register a methods by assigning it using the operator += you actually call an IL method which is Combine which combines the method IL to the IL this delegate is pointing to!
To Be Continued….
Thank you for the great information. I look forward to seeing more articles and what else you have to offer!