sde Posted March 2, 2004 Posted March 2, 2004 I've spent the last day trying to wrap my head around the concept of delegates. I finally understand how to use them ( somewhat ) , but I don't understand entirely 'why' to use them. Anyone have a link to a great explanation or tutorial on this ? Quote codenewbie
TechnoTone Posted March 2, 2004 Posted March 2, 2004 One of the most obvious uses is on a wizard. You can change the delegate for the "Next" button as you progress through the wizards stages, for example. Quote TT (*_*) There are 10 types of people in this world; those that understand binary and those that don't.
Joe Mamma Posted March 6, 2004 Posted March 6, 2004 (edited) There are two area that traditional VB programmers are going to have a hard time wrapping their heads around the .NET framework: Delegates and reflection. Delegates are basically method references. They are an extremely strong feature of any OOP language. They take some inginuity to use them effectively. They give the ability to dynamically specify application behavior. I refer you to this gentlemans post in the databases thread: Database record problems...no clue! this code could be reduced to 3 lines [edit]I removed some inappropriate comments. -Derek[/edit] private void CheckedChangedHandler(Object sender, EventArgs e) { System.Windows.Forms.RadioButton btn = sender as System.Windows.Forms.RadioButton; if (btn != null) strSearch = btn.text; } } and in the form load event,for each radio button do the following selectOption1.CheckedChanged += CheckedChangedHandler(EventArgs.Empty); selectOption2.CheckedChanged += CheckedChangedHandler(EventArgs.Empty); selectOption3.CheckedChanged += CheckedChangedHandler(EventArgs.Empty); selectOption4.CheckedChanged += CheckedChangedHandler(EventArgs.Empty); selectOption5.CheckedChanged += CheckedChangedHandler(EventArgs.Empty); selectOption6.CheckedChanged += CheckedChangedHandler(EventArgs.Empty); You see, EventHandler is a delegate declared: public delegate void EventHandler(Object sender, EventArgs e); Events are a specific application of delegates, basically delegate properties: public MyClass { EventHandler onChange; public Event Change { get { return onChange; } set { onChange = value; } } } by assigning events at run-time, behavior can be dynamic. By deriving custom EventArgs you can create some real neat behavior. Boy too much to go into here, but they are important!!!! Joe Mamma Edited March 6, 2004 by Derek Stone Quote Joe Mamma Amendment 4: The right of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures, shall not be violated, and no warrants shall issue, but upon probable cause, supported by oath or affirmation, and particularly describing the place to be searched, and the persons or things to be seized. Amendment 9: The enumeration in the Constitution, of certain rights, shall not be construed to deny or disparage others retained by the people.
pas30339 Posted March 6, 2004 Posted March 6, 2004 One 'why' has to due with GUI's. The user performs an action on one form, and you want to update all controls that are interested in what the user did on an application wide basis. A value is changed in formA and a datagrid in formC recalculates it's totals based on the new value. The delegate acts as the bridge allowing communication from the object raising the event to objects interested in knowing about the event. Quote
Denaes Posted March 8, 2004 Posted March 8, 2004 Not to get back on topic, but... I'm reading this pretty damn cool book by O'Reilly called Object-Oriented Programming with Visual Basic.Net. Friggin genius book. Talk about bare bones. 3 chapters in and you're still using notepad, the framework compiler and a console screen to compile modules, dll's and console based programs (with notes on changes you'd make with a windows program) I get to the section on delegates and a few pages are spent on them. True to what Joe Mama said, they were complex and promised to be very important. I didn't have any trouble with the concept (despite being a VB programmer), but I was in a bus reading it. I really need to go back over it with the computer. The next section was on Events. They looked similar to Deleagates in the examples he was using them. Then he had like a little notebox saying that An event is pretty much just like a Delegate for most purposes. In fact, an Event decompiles down to a delegate in MSIL, and you'd use them to do pretty much the same exact thing. He advised learning delegates, because they did have their uses, but said tha Events were much more common. One of the exercises in the book was to rewrite a twin pair of programs (a debugger console and debugger program) using events rather than the delegates he used. I've been reading that book for one day... just straight reading... and I've learned so much. Quote
Joe Mamma Posted March 8, 2004 Posted March 8, 2004 If I am not mistaken, Event is just a keyword that modifies delegates so they appear in the property explorer and allow the compiler to perform consumption and chaining(is that the right term?) delegates are simply a user defined type that is the format for a method - At the risk of being censored ;) , I am going to use delphi syntax here because it really drives the concept home: in delphi you can do the following type TMyMethod = procedure(sender: TObject); var MyMethod: TMyMethod; procedure Method1(sender: TObject); begin // do domething with sender end; procedure Method2(sender: TObject); begin // do domething with sender end; begin if [some runtime specified boolean value such as a check box] then MyMethod = Method1 else MyMethod = Method2; MyMethod(Application); end. So, TMyMethod is a definition delegating any function that takes a single argument of type TObject; I declare a variable of type TMyMethod, MyMethod . I declare two methods that take a single argument of type TObject, making them eligable for delegation by a variable of type TMyMethod. at run time, the program does some dynamic analysis and assigns the appropriate method to MyMethod and then executes the method using the application variable as the argument. now. . . open mind time. . . use your imagination. . . arrays can contain any type of data and can be loaded dynamically at runtime. . . consider an array of delegates, the actual methods being delegated are specified at run time depending on the user specified option selections. . . After iterating through the array and executing the user specfied methods, the user can select a set of different options. the program loads the new delegated methods based on the selections and the program executes with a completely different behavior. Again, I highly suggest that anyone new to OOP download delphi. not because delphi is the end all be all of programming languages but because delphi comes with vitually ALL the source used to devlop the delphi components. It is a wonderful source for ideas and examples of real world OOP technique that transcends syntax. Oh yeah, and its type library editor is phenomenal! Joe Mamma. . . free your mind - vote Kerry!!! :D Quote Joe Mamma Amendment 4: The right of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures, shall not be violated, and no warrants shall issue, but upon probable cause, supported by oath or affirmation, and particularly describing the place to be searched, and the persons or things to be seized. Amendment 9: The enumeration in the Constitution, of certain rights, shall not be construed to deny or disparage others retained by the people.
*Experts* Nerseus Posted March 8, 2004 *Experts* Posted March 8, 2004 A delegate creates a new variable type and is used to define what a function looks like (it's params and return type) so that you can call a function dynamically, in a type-safe way. Similar to defining a class, a delegate just provides a definition of what it should look like. This is similar to an interface in that you're not providing code, only what it should look like. Unlike an interface, it's just for a function and you CAN instantiate a variable of that type. The most common use for delegates is for handling events. If you use WinForms, then every event you use is defined in the system as a delegate. When you double click on a control in Winforms to create an event, it creates code something like the following (in C#): // In InitializeComponent: this.Load += new System.EventHandler(this.Form1_Load); // Outside of InitializeComponent - just somewhere in the class: private void Form1_Load(object sender, System.EventArgs e) { } Somewhere in System MS has defined a delegate that looks like this: delegate void EventHandler(object sender, System.EventArgs e); Visual Studio takes care of adding the "this.Load += ..." code for you as well as defining a function that matches what the delegate wants. Delegates can be single or multicast as well. What does that mean? Simply, if you add more than one "handler" for the delegate, it becomes multicast. That means that when you call the delegate, which looks like a function call, it will actually call more than one function. This is ideal for events since more than one piece of code may want to handle an event. Here's a sample in C#: public class Form1 : System.Windows.Forms.Form { // The delegate, just the definition of what a function will look like delegate void Test(); // A function that matches the definition of the delegate above private void TestA() { System.Diagnostics.Debug.WriteLine("TestA"); } // A function that matches the definition of the delegate above private void TestB() { System.Diagnostics.Debug.WriteLine("TestB"); } // Constructor public Form1() { // Define an instance of the delegate Test t = new Test(TestA); // Add a second handler to the delegate t+= new Test(TestB); // Call the delegate - will call both functions, TestA and TestB. t(); } ... } -Nerseus Quote "I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.