Delegates,Events and Lambda Expressions
While developing applications, there might be a situation where you need to use events in your program.To successfully accomplish these tasks in your program,you need a DELEGATE. EVENT' An EVENT is a way for a class to provide notification when something interesting happens. Lambda'can be used to create expression types or delegates.
While developing applications, there might be a situation where you need to
• Use events in your program.
• Improve overall performance by calling certain methods,
• Or even invoke methods with one call.
To successfully accomplish these tasks in your program , you need delegates.
In essence, a delegate is a type-safe object that points to another method in the application , which can be invoked at later time.
Delegate declaration :
[attributes][modifiers]delegate result-type identifier ([formal parameters]);
attributes(optional):Additional declarative information.
modifiers(optional):the allowed modifiers are public, protected, internal and private.
result-type:The result-type which matches the return type of the method.
formal-parameters:Parameter-List,If parameter is a pointer the delegate must be declared with unsafe modifier.
delegates are the basis for events.
Note*: A delegate can invoke either an instance method associated with an object or an static method associated with class. All that matters the return type of the delegate.
delegate double Mydelegate(double X);
static void DemoDelegates()
//Creating and instantiating a delegate and a delegate instance
MyDelegate delInstance=new MyDelegate(Math,Sin);
//Invoking a method attached to instance
An Event is a way for a class to provide notification when something of interest happens.
Example: A Class that encapsulates a user interface control might define an event to occur when user click the control.
The control class does not care what happens when the button is clicked.
However, it needs to tell derived classes that the click event occurs.
Derived classes can choose how to respond.
//Declare a delegate for an event
delegate void MyEventHandler();
//Declare an Event class
public event MyEventHandler MyClick Event;
//This is called to fire the event.
public void InvokeClickEvent()
Provide concise, functional syntax to write anonymous methods.
you may write them as a parameter list followed by the '=>' token .followed by an expression or statement block.
Can be used to create delegates or expression tree types.
The left side of the lambda operator specifies input parameters (if any) and the right side holds the expression or statement block.
delegate int del(int i)
int j=myDelegate(5); //j=25