: A delegate is merely a managed function pointer. When you declare a delegate such as:
:
:
: public delegate void DoSomethingDeleg();
:
:
: The compiler generates a class that wraps a function that takes no arguments and returns void. Take a look at this example C# Console App:
:
:
: using System;
:
: namespace DelegCSharp
: {
: public delegate void DoSomethingDeleg();
:
: /// <summary>
: /// Summary description for Class1.
: /// </summary>
: class Class1
: {
: /// <summary>
: /// The main entry point for the application.
: /// </summary>
: [STAThread]
: static void Main(string[] args)
: {
: DoSomethingDeleg doIt = new DoSomethingDeleg(SaySomething);
: doIt += new DoSomethingDeleg(SaySomethingElse);
:
: doIt();
: }
:
: public static void SaySomething()
: {
: Console.Write("Hello");
: }
:
: public static void SaySomethingElse()
: {
: Console.WriteLine(" World");
: }
: }
: }
:
:
: This line:
:
:
: DoSomethingDeleg doIt = new DoSomethingDeleg(SaySomething);
:
:
: Creates a function pointer to the function called SaySomething.
:
: This line:
:
:
: doIt += new DoSomethingDeleg(SaySomethingElse);
:
:
: looks strange, but to explain, delegates maintain a list of function pointers of the same type. The += operator says to add another function to that list. This is called multicasting and in fact the class that the compiler generates for the delegate, derives from MultiCastDelegate.
:
: Finally, this line:
:
:
: doIt();
:
:
: Calls all the functions in the delegate, in the order they were added. So basically this single line of code calls the SaySomething function followed by the SaySomethingElse function. Cool huh.
:
: Delegates are also used for generating call backs:
:
:
: public static void CallBackSayIt(DoSomethingDeleg sayIt)
: {
: if(null != sayIt)
: sayIt();
: }
:
:
: To use this function you could ...
:
:
: CallBackSayIt(new DoSomethingDeleg(SaySomething));
:
:
: Delegates are also used to handle events and such. Also, you are probably wondering why a delagate is needed to set the property of a text box control on the main thread from a secondary thread. The reason is because delegates are always triggered from the main thread.
:
: Delegates are difficult to get use to, but with practice, you can accomplish some advanced techniques.
: ---------------------------------------------------------------------
:
: Object
: ------
:
: All classes derive directly or indirectly from an object variable. You can store anything in an object.
:
:
: object obj = 17;
: obj = "Hello";
: obj = new StringBuilder();
: // etc ...
:
:
Thanxz