![]() |
|
C# Delegates, Free online C# Programming Tutorial... |
| Lessons | C# Delegates |
|
An example of delegates is shown below: public delegate void Print (String s); public void realMethod (String myString) { // method code } public void realMethod2 (String myString) { // method code } public void realMethod3 (String myString1, String myString 2) { // method code } Another method in the class could then instantiate the 'Print' delegate in the following way, so that it holds a reference to 'realMethod': Print delegateVariable = new Print(realMethod); Then invoking the realMethod() through delegateVariable is pretty straight forward: delegateVariable(); To add additional method to the delegate we use the += operator as demonstrated below: delegateVariable += realMethod2; An important thing to remember is that whatever method you add to a delegate its signature must match to the delegate type. In the above example the Print delegate can take any method that takes a single string as an argument. If we try to add a method that has a different signature, a compile time error is generated. For example the following code will not compile: delegateVariable += realMethod3; // compile time error!
Next >>> Lesson No. 23: C# Events
|