what is the main difference between delegate and an event in c#?

what is the main difference between delegate and an event in c#?

Delegate:-A delegate is basically a reference to a method. A delegate can be passed like any other variable. This allows the method to be called anonymously, without calling the method directly. 
 delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure.

The delegate declaration takes the form:

[attributes] [modifiers] delegate result-type identifier ([formal-parameters])
Event:-An event in one program can be made available to other programs that target the .NET runtime.
An event is a member that enables an object or class to provide notifications. Clients can attach executable code for events by supplying event handlers. Events are declared using event-declarations: 

event-declaration: 
event-field-declaration
event-property-declaration 
event-modifier: 
new
public
protected
internal
private
static 


Example:-
 public delegate void EventHandler(object sender, Event e);
public class Button: Control
{
   public event EventHandler Click;
   protected void OnClick(Event e) {
      if (Click != null) Click(this, e);
   }
   public void Reset() {
      Click = null;
   }
}


By:kamal
Date:2013-10-10 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related C Links

C interview questions and answers for experienced and fresher