tags:

views:

106

answers:

6

Can anyone place some clear examples of using Events in C# (or any .NET language)? There are plenty of such on the internet, but most of them are complicated and they don't apply to every situation. Make it universal if possible please.

+1  A: 

From your post, it appears that you want an "example" which would "apply to every situation" while being "universal" and "practical". I don't see how that is possible.

If you simply want to understand events better, start here. You could find something shorter, but it might not be clearer.

John Fisher
I need a short example - a piece of code, to see how it works.
Johnny
+1  A: 
  • Giving progress updates and completion on tasks.
  • Reacting to user input
  • Timers
McAden
+2  A: 

Events are the basis of event-driven programming (obviously). So an event is appropriate any time you want to take action(s) based on something else occuring. What that something else could be a myriad of things - a user clicking a button, a timer elapsing, a window being closed, etc. It's hard to make it really universal, since there are so many different scenarios.

One example would be to fill a label with text when the user clicks on a button:

btnMyButton.Click += (o, ev) => { SetTextLabel(label1, "You clicked the button"); };

Note that SetTextLabel is a function that you would provide, and it should be ThreadSafe (otherwise I would get pounded by commenters saying my code wasn't so.)

Michael Bray
That's using predicate as function (I know it's delegate)? Nice one, didn't know that!
Johnny
Yeah it's wonderful for relatively short event handlers, although in a normal Windows form it kind of defeats the point of having a designer... I typically wouldn't use it this way for form events, but for events that other (non-UI) objects expose. Note that in this example, I don't use the `object o` or `System.EventHandler ev` but you certainly could use them.
Michael Bray
Well I'm not gonna use this for WinForms, at least WinForms aren't the reason I asked this. However, could you tell me something about ev, it's `System.EventArgs` I supose, how can I use it?
Johnny
The System.EventArgs class itself isn't really very useful, but by convention events of UI controls tend to have a signature of SomeEventHandler(object sender, SomeEventArgs e) where SomeEventArgs is a class that derives from System.EventArgs. There are some events, such as Form.Closing, that pass a System.ComponentModel.CancelEventArgs object as the second parameter. That class has a Cancel property that you can choose to set in your event handler code, allowing you to interrupt the action that the control is currently executing. There are various EventArgs classes with different purposes.
Dr. Wily's Apprentice
@Dr Wily: Very well stated. It's also another reason why this particular format is nice - the compiler naturally understands the exact type of the event, so it doesn't have to be declared. One could argue however, that it does reduce readability because although the compiler knows the type, it's not obvious by looking at the code. If that is a concern, one could include the type definition as (object o, EventArgs ev) or whatever the type actually is.
Michael Bray
+2  A: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class EXMAPLE 
    {
        public event EventHandler Changed;
        protected string _content;

        public string Content{
            get { return _content; }
            set 
            {
                _content = value;
                OnChanged(EventArgs.Empty);
            }
        }

        // Invoke the Changed event; called whenever list changes:
        protected virtual void OnChanged(EventArgs e)
        {
            if (Changed != null)
                Changed(this, e);
        }
    }


    class Program
    {
        private static void EXAMPLE_CONTENT_CHANGED(object sender, EventArgs e)
        {
            EXMAPLE ex = (EXMAPLE)sender;
            Console.WriteLine(ex.Content);
        }

        private static void INNA_REAKCJA(object sender, EventArgs e)
        {
            Console.WriteLine("The Content of EXAMPLE was changed");
        }


        static void Main(string[] args)
        {
            EXMAPLE ex1 = new EXMAPLE();
            EXMAPLE ex2 = new EXMAPLE();

            //add event ;->
            ex1.Changed += new EventHandler(EXAMPLE_CONTENT_CHANGED);

            ex2.Changed += new EventHandler(EXAMPLE_CONTENT_CHANGED);
            ex2.Changed += new EventHandler(INNA_REAKCJA);  

            //test
            ex1.Content = "value 1";
            ex2.Content = "value 2";

            System.Console.ReadKey();
        }
    }
}

That is only simple example - not universal ;p

nilphilus
Practical use is shown pretty clear here, nice one!
Johnny
+2  A: 

The most simple example is when your creating a form which contains a clickable control such as a button. When you double click on the button, Visual Studio will generate an event in the code behind pointing to a method that will be called when the event gets fired off.

this.MyButton.Click += new System.EventHandler(this.MyButton_Click);

In general events are basically messages sent by an object to notify other objects that an action has occurred.

Mez
Quite useful, you've just put a short and clear example how to do it.I supose `this.MyButton.Click` is an EventHandler object?
Johnny
MyButton_Click is a method declared with the EventHandler signature.
Mez
A: 

Events is the current way of handling user interface interaction with the rest of the application. Microsoft future into event driven development depends on the future of this new technology called RX Extensions, though (seems very promising). Java has the Actionlistener component (coming from the observer pattern), if you know it and can evaluate the usability of Events (in UI). Events in general is the mechanism with which notifications are provided to the referring object when something happens.

Check the relevant tutorial from msdn also.

Example:

    List.Changed -= new ChangedEventHandler(ListChanged);

Here the developer hooked up the method which will be called with the rising of the Changed event of the List container. So, when the list will change (added, or removed an item), this method will be called.

Aggelos Mpimpoudis
This RX Extensions look very promising. Thanks for the info.
Braveyard
I might check this Rx out as I progress, thanks for the tip!
Johnny
Yes, Erik Meijer is doing some great work. Check channel9 for more. There are plenty of videos explaining this new paradigm. ;););)
Aggelos Mpimpoudis