Delegates
-
Can anybody show me the shortest example on using a delegate? Im just trying to gather ideas on how to program in "keep it short and simple way" :) "To teach is to learn twice"
The shortest example? Well I guess that would be...
class T{delegate void D();static void Main(){D d = new D(Main);d();}}
...but watch out for the stack overflow. -- -Blake (com/bcdev/blake)
-
Can anybody show me the shortest example on using a delegate? Im just trying to gather ideas on how to program in "keep it short and simple way" :) "To teach is to learn twice"
The shortest example? Well I guess that would be...
class T{delegate void D();static void Main(){new D(Main)();}}
...but watch out for the stack overflow. I suppose you'd like a useful example?
class Example {
delegate void StatusOutput(string text);static void Main() { DoSomeWork(new StatusOutput(System.Console.WriteLine)); DoSomeWork(new StatusOutput(Alert)); } static void Alert(string text) { System.Windows.Forms.MessageBox.Show(text, "Status Update"); } static void DoSomeWork(StatusOutput output) { output("Working..."); System.Threading.Thread.Sleep(2000); output("Done"); }
}
That was about the shortest meaningful use I could think of. A delegate is an object that wraps a method. You can then pass this object around and use it later to call the method. There are lots of other more advanced uses, like invoking them asynchronously, but that's a start. -- -Blake (com/bcdev/blake)