views:

52

answers:

4

I have learned delegate in dotnet that is referencing any function.

What does it mean by event coceptually? Is it any reference ? It has a middle layer and use delegates internally. But, what is that middle layer ?

Actually, what can we do using event ? or Why should we use it ?

Why does event has no return type ? Why is it public by default ?

+1  A: 

An event is like a collection of function that will be called whenever the 'event' occurs. Since it's usually fire and forget, no return type is needed.

Adrian Godong
I think OP will be more confused between events and delegates by this answer. I agree that answer is absolutely correct.
Ismail
I didn't write anything about delegate (which, if the OP wants to know, is some sort of 'function container' that converts functions to objects).
Adrian Godong
+2  A: 

I think of an event as a collection of delegated methods. You can subscribe as many event handlers to an event as you want.

You create an event when you want to expose a point in your code that someone can "inject" operations. For example, let's say you have a class that is responsible for processing an order. You may want to expose an event called "OrderProcessed" and in the future someone who is using your order processing class could "hook up" to the OrderProcessed event to do something like send a confirmation email. Because the event is a delegate type, you can specify that all methods subscribing to the event expect to receive a parameter that contains your "Order" type

Example:

public class OrderEventArgs : EventArgs
{
     public MyOrderClass Order { get; set; }
     public Boolean Processed { get; set; }

     public OrderEventArgs(MyOrderClass order, Boolean processed)
     {
         Order = order;
         Processed = processed;
     }
}
public class OrderProcessor
{
     public delegate void OrderEventHandler(Object sender, OrderEventArgs e);

     public event OrderEventHandler OrderProcessed;

     public void ProcessOrder(MyOrderClass order)
     {
          //process the order...

          if(OrderProcessed != null)
               OrderProcessed(this,new OrderEventArgs(order,true));
     }
}
matt-dot-net
A: 

Hope this will make things clear to you

http://www.akadia.com/services/dotnet_delegates_and_events.html

Ismail
+1  A: 

In ordinary English, when you subscribe to an event, you are notified when it occurs, along with zero or more arguments.

So, object1 might say "Hey, when someone clicks btn1, I wanna do {delegate to function that pops up a MessageBox }"

And object2 might say "Hey, when someone clicks btn1, I wanna do {delegate to function that writes to a log }"

When someone then presses the button, each subscriber is told, and does whatever its delegate says.

Carlos