Tech Off Thread

10 posts

basic C# question

Back to Forum: Tech Off
  • katana_234

    Hi guys, it is my first time posting here in channel9, so please if I made a mistake, please tell me.

    I am currentlly learning C#, but I couldn`t understand the Event and the Event Handler, can some one help me with it? I have read the documentation in the library of the C# express edition but I didn't managed to understand it very well.

    And thank you in advance.

  • littleguru

    The even is an implementation of the observer design pattern. The idea is that you can register for something to happen and once it happens you get informed about that.

    In concrete you register an event (is something that happens) of an object instance. And that instance is going to inform you when something happens...

    Example:

    // First we create an instance of the Button class. This is a normal
    // button that can be clicked.
    Button btn = new Button();
    // Now we register the Click event. That means we get notified each
    // time the button got clicked. The btn_Click is a method that is
    // going to be called when the button gets clicked.
    btn.Click += new EventHandler(btn_Click);

    // That's the method that is going to be called.
    private void btn_Click(object sender, EventArgs e)
    {
        // Here we do something with the event.
        // For example show a message box.
        MessageBox.Show("Hello World!");
    }

    In the example we registered the Click event. Registering means we told the button to call the method that we provided, when somebody clicked it. The += is just notation: it means that we want to register this method (= have it called when a click happens). There is also -= which would mean that we don't want that method called anymore.

    new EventHandler is a delegate. In .NET you can't directly give to the event a method. This doesn't work:

    btn.Click += btn_Click;

    You need to encapsulate (wrap) it in a delegate. A delegate is something that points to a method. It holds a method and says: if you call me I'm going to call that method for you. The delegate defines also what arguments that method has: that's required because everything is type-safe in .NET. The general EventHandler delegate defines the method's arguments with object sender, EventArgs e

    I hope this helps Smiley

  • Andrew Davey

    littleguru wrote:
    new EventHandler is a delegate. In .NET you can't directly give to the event a method. This doesn't work:

    btn.Click += btn_Click;



    Um, yes you can in C# 2.0. I use it all the time Smiley It makes the code much cleaner to read.

  • vesuvius

    Hello Katana,

    You may want to check video3 at the Beginner Developer Learning Center at MSDN. Events are very simple in essence, but the concepts aren't always simple to understand first up.

    Ultimately most useful things you will do (program) will be based on an Event in windows so try not to stress yourself if you can't grasp it. After programming a while you'll wonder how you ever misunderstood them.

  • littleguru

    Andrew Davey wrote:
    
    littleguru wrote:
    new EventHandler is a delegate. In .NET you can't directly give to the event a method. This doesn't work:

    btn.Click += btn_Click;



    Um, yes you can in C# 2.0. I use it all the time Smiley It makes the code much cleaner to read.


    I didn't know. Nice to know. Thanks!

    But: just to make that clear. Internally the compiler is getting the arguments and creating the delegate for you.

  • katana_234

    thanx alot guys for the help Big Smile, I will check the information that you have gave me and I will see what I can do.

  • Ion Todirel

    littleguru wrote:
    
    Andrew Davey wrote:
    
    littleguru wrote:
    new EventHandler is a delegate. In .NET you can't directly give to the event a method. This doesn't work:

    btn.Click += btn_Click;



    Um, yes you can in C# 2.0. I use it all the time Smiley It makes the code much cleaner to read.


    I didn't know. Nice to know. Thanks!

    But: just to make that clear. Internally the compiler is getting the arguments and creating the delegate for you.
    btw its called delegate inference or method group conversions or whatever

  • katana_234

    Guys, Can some one give me some examples that runs on the console,  I mean without the GUI?

  • littleguru

    This is an example that prints just on each time the timer event fires "Elapsed" on the console:

    class Program
    {
        static void Main(string[] args)
        {
            // Set up a timer and make it run.
            System.Timers.Timer timer = new System.Timers.Timer(1000);
            // Tell the timer to call the "timer_Elapsed" method on each time the interval specified
            // in the constructor of the timer has been reached.
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            // Start the timer.
            timer.Start();

            // Wait for the user to enter a line (for example press the ENTER key).
            Console.ReadLine();
        }

        static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Console.WriteLine("Elapsed");
        }
    }


    You might just copy it into a console application project (replace the Program class there) and run it.

  • bdesmet

    Maybe it's useful to show a more complete sample containing an event definition as well.

    Let's start with the concept of a delegate, which is an object that can point to a method with a given signature:

    delegate int BinOp(int a, int b);

    BinOp can point to any method that takes two ints and returns an int. For example:

    int Add(int a, int b) { return a + b; }

    can be pointed at by a BinOp delegate, like this:

    BinOp add = new BinOp(Add);

    or even (starting from C# 2.0):

    BinOp add = Add; //the same as the code above, just more convenient

    One can call the target method a delegate is pointing at by using regular method call syntax on the delegate instance, like this:

    add(1,2); //notice the casing of add - we're not calling Add directly but through the delegate created above

    For the following, consider a delegate defined like this:

    delegate void ChangedEventHandler(object o, ChangedEventArgs e);

    Note: there's a generic EventHandler class that provides a shortcut to create typical *EventHandler delegates.


    Now we can cook up an event using this delegate. This allows users of a class to "subscribe" to an event by pointing at a method with the appropriate signature:

    class Controller
    {
       public event ChangedEventHandler StateChanged; //events have a delegate type, in this case ChangedEventHandler

       public void DoWork()
       {
          //do work
          if (StateChanged != null) //make sure someone has subscribed
             StateChanged(this, new ChangedEventArgs(...)); //delegate calling syntax
          //do more work
       }
    }

    This allows the user of the class to subscribe to the event like this:

    Controller ctrl = new Controller();
    ctrl.StateChanged += new ChangedEventHandler(ctrl_Changed);

    where ctrl_Changed is defined like this:

    void ctrl_Changed(object o, ChangedEventArgs e)
    {
       //do something to handle the event; o points at the object that raised the event - you can cast it back to Controller
    }

    Or, using anonymous method syntax in C# 2.0 and higher:

    Controller ctrl = new Controller();
    ctrl.StateChanged += delegate (object o, ChangedEventArgs e)
    {
       //do something to handle the event; o points at the object that raised the event - you can cast it back to Controller
    };

    Hope this helps.

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.