tags:

views:

33

answers:

3

Hi, I thought I understand the events in C#. That sometimes they are used if you do not want to call the method directly rather than left place for custom implementation. But when?

Programmer A writes class A, programmer B writes class B. Class A should raise an event that Class B register and reacts but Class A does not know anything about function that class B uses for serving.

Could you please provide me with simple example?

+1  A: 

This is pretty basic and gets the point across.

http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx

Steve H.
+1  A: 
public class A
{
    private readonly B _B = new B();

    public class A() 
    {
        _B.MyEvent += MyEventHandler; 
    }

    private void MyEventHandler(object sender, EventArgs e)
    {
        // Handle
    }
}

public class B
{
    public event EventHandler MyEvent;

    // Call this when you raise the event so you don't 
    // need check if MyEvent is null.
    private void OnMyEvent() 
    {
        if (MyEvent != null) // If this is null we have no subscribers.
        {
            MyEvent(this, EventArgs.Empty);    
        }
    }
}
ChaosPandion
A: 

When you say "they are used if you do not want to call the method directly rather than left place for custom implementation", you make me think that you may not completely understand the difference between a simple delegate and an event. Way oversimplifying here but here's a brief explanation...

Delegates are a way of letting someone who is writing code using your code to provide their own method. As such, they don't go through the message pump and occur synchronously etc.

Events use a delegate to provide a way for you to put your own code in to respond to the event. Events go through the message pump and are appropriate when there is something you need to respond to that may be happening elsewhere. However, they will occur outside of the execution path of the currently executing code.

Happily, most people seem to get when to use one or the other by instinct. Again, gross simplification here, but hopefully enough for further reading.

Jim Leonardo