Delegates And Events - The Uncensored Story (page 2)
http://www.csharpfriends.com
World's Greatest C# Community    
Home Articles C# Forums Books C# Syntax C# Spec C# Jobs free Source Code Advertise About
 

Control Panel

[ Sign In / register ]
Points   
Notes 
My Forums
My Tutorials
My Profile

Resources

Learn
 Articles
 QuickStarts
 C# Spec
 Whitepapers
 Tools
 Class Browser
 C# Code Generator
 Links
 Misc Rss Feeds
 Code Highlight
 411 Directory
 FREE magazines
 freevb.net

Reviews
  ASP.NET Hosting

Source Code
 Get Version 1.0



C# Consulting
AspDotNetStoreFront
Chapter:   UnCategorized
Current Lesson:
Delegates And Events - The Uncensored Story (page 2)
[Latest Content]
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | ALL
[prev. Lesson]  Delegates And Events - The Uncensored Story [next Lesson]  abstract keyword
Delegates And Events - The Uncensored Story (page 2)
  by: Salman Ahmed

Delegates And Events - The Uncensored Story - Part 1
By A. Abdul Azeez


Back to Page 1 Now let us take a look at the whole button class, (page 2)
class button
{
    private ButtonEventHandler beh=null; // For click
    private ButtonEventHandler bep=null; // For press
 
    public void AddOnClick(ButtonEventHandler handler)
    {
        Console.WriteLine("Adding click event handler");
        beh=(ButtonEventHandler)Delegate.Combine(beh, handler);
    }
 
    public void RemoveOnClick(ButtonEventHandler handler)
    {
        Console.WriteLine("Removing click event handler");
        beh=(ButtonEventHandler)Delegate.Remove(beh, handler);
    }
 
    protected virtual void OnClick(ButtonEventArgs e)
    {
        if (beh!=null)
        {
        beh(this, e);
        }
    }
 
    public void AddOnPress(ButtonEventHandler handler)
    {
        Console.WriteLine("Adding Press Event handler");
        bep=(ButtonEventHandler)Delegate.Combine(bep, handler);
    }
 
    public void RemoveOnPress(ButtonEventHandler handler)
    {
        Console.WriteLine("Removing Press Event handler");
        bep=(ButtonEventHandler)Delegate.Remove(bep, handler);
    }
 
    protected virtual void OnPress(ButtonEventArgs e)
    {
        if (bep!=null)
        {
        bep(this, e);
        }
    }
 
    public void click()
    {
        ButtonEventArgs bea=new ButtonEventArgs("clicked");
        OnClick(bea);
    }
 
    public void press()
    {
        ButtonEventArgs bea=new ButtonEventArgs("pressed");
        OnPress(bea);
    }
}

Now let us begin a line by line walkthrough of the above code,
private ButtonEventHandler beh=null; // For click
private ButtonEventHandler bep=null; // For press
The above two lines declare two delegates. Both these delegates are multicast delegates. They represent the series of method calls that have to take place when an event occurs. They are initialized to null to indicate that they point nowhere when the class is first instantiated. I am using two delegates here because I assume that separate delegates are used to track separate events. In the code snippet above, the delegate beh would handle click calls and the delegate bep would handle press calls.
public void AddOnClick(ButtonEventHandler handler)
{
   Console.WriteLine("Adding click event handler");    
   beh=(ButtonEventHandler)Delegate.Combine(beh, handler);
}
The AddOn methods are used to add a list of methods that need to get called when an event occurs. Thus it is natural that it receives a delegate as a parameter which in turn points to a function. Depending on the number of methods that needs to be invoked when an event occurs, this method is invoked multiple times passing the appropriate delegate parameter. The situation can be better explained with the help of a figure,
beh ------> ButtonEventHandler1 -----> &Fn1()                  
            ButtonEventHandler2 -----> &Fn2()
            ButtonEventHandler3 -----> &Fn3()
            ButtonEventHandler4 -----> &Fn4()
As the figure above shows, the beh pointer points to a delegate which in turn points to a function. In the case of multicast delegate, there is a prev field which gets initialized to null when the delegate is constructed. Now when you invoke the combine method as shown in the code snippet above, the prev field of handler points to beh. Thus when many delegates are combined using a Combine method, what internally happens is that a linked list gets created. That is why when we invoke the delegate from the OnClick or OnPress methods we find that all the functions combined get called. This makes it possible for multiple clients to receive notification about an event. This is the funda behind multi cast delegates. The same explanation applies to RemoveOn methods. 4. The Form Simulation In our form example explained in the beginning of the article we had a form class derived from Form which constructed a button and attached event handlers. We are going to simulate the same but the only difference would be that we would not be creating a GUI but would instead have a client which adds our simulated button class and attaches event handling methods to it. For a change, instead of explaining the source code in bits and pieces let me put in explanations in the source code itself. The code for the client class is as follows,
public class DelegatesAndEvents
{
    //Declare the simulated button class
    private button button1=new button();
 
    //Have a private constrcutor
    private DelegatesAndEvents()
    {
        /*

        Now start adding onclick and onpress events on the button class by passing the appropriate
        methods to which calls should be routed. What is being done below is that three methods
        are being added to the same OnClick event so that when the Click event is raised the
        delegate would call all the methods
        */

        button1.AddOnClick(new ButtonEventHandler(ClickEventHandler1));
        button1.AddOnClick(new ButtonEventHandler(ClickEventHandler2));
        button1.AddOnClick(new ButtonEventHandler(ClickEventHandler3));
        button1.AddOnPress(new ButtonEventHandler(PressEventHandler));
        button1.click();
        button1.press();
    }
 
    public static void Main(String [] args)
    {
        DelegatesAndEvents d=new DelegatesAndEvents();
    }
 
    public void ClickEventHandler1(object sender, ButtonEventArgs e)
    {
        Console.WriteLine("click event handler1");
        Console.WriteLine(e.msg);
        Console.WriteLine("after");
    }
 
    public void ClickEventHandler2(object sender, ButtonEventArgs e)
    {
        Console.WriteLine("click event handler2");
        Console.WriteLine(e.msg);
        Console.WriteLine("after");
    }
 
    public void ClickEventHandler3(object sender, ButtonEventArgs e)
    {
        Console.WriteLine("click event handler3");
        Console.WriteLine(e.msg);
        Console.WriteLine("after");
    }
 
    public void PressEventHandler(object sender, ButtonEventArgs e)
    {
        Console.WriteLine("press event handler");
        Console.WriteLine(e.msg);
        Console.WriteLine("after");
    }
}
Conclusion

What goes on behind the scenes when event handlers are added? How do delegates aid in this? How can the event handling in a class be simulated, how do do multiple methods get called when a particular event has been raised etc. have been the core points of discussion dealt with in this article. I hope that the explanations would have helped in bringing about some amount of clarity. Some aspects are only internally known to the runtime and no effort has been made to dwelve into them. One such example is how does the click event get raised when the button is actually clicked. The article has focused only on what is absolutely necessary for us to understand the way delegates and events interrelate in the context of an event handler.

1 


Build Your Own ASP.NET Website Using C# & VB.NET

Chapter:  UnCategorized
Current Lesson:
Delegates And Events - The Uncensored Story (page 2)
[Latest Content]
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | ALL
[prev. Lesson]  Delegates And Events - The Uncensored Story [next Lesson]  abstract keyword


Today's Top Movers
vulpes 6800
MadHatter 2220
jal 867
Jeff1203 857
muster 791

Yesterday Top Movers
shakti sin.. 9
MadHatter 3
C#fanatic 2
Al_Pennywo.. 2
lilica 1

Monthly Leaders
vulpes 6800
MadHatter 2260
jal 867
Jeff1203 857
muster 791

Top Members
mosessaur 18457
Rincewind 7074
stanleytan 6995
vulpes 6800
Gsuttie 6046

Great Offers
.net hosting
Go To My Pc
Remote Pc Control
zonealarm
spam blocker
web hosting directory
ad server   C#
snadtech GoToMyPc

Top of Page

Advertise | About | Link To Us | Privacy Notice Copyright © 2003 - 2005 CSharpFriends.com  All Rights Reserved  Visual C# Developer Center