Tags

,

4 different ways are there to link Event handler to Event

1. Creating new delegate instance of our custom delegate

Eg:

public delegate int CalculateTotal(int x, int y);
public class OfferNumber
{
 public event CalculateTotal totalDelegate;
}
public class EventSampleNewDelegateInstanceCreation
{
 public void DelegateAccess()
 {
 OfferNumber number = new OfferNumber();
//Example for NewDelegateInstanceCreation
 number.totalDelegate += new CalculateTotal(sample);
 }
private int sample(int x, int y)
 {
 throw new NotImplementedException();
 }
}
2. Using Delegate Inference,
Eg:
 public class EventSampleDelegateInference
 {
 public void DelegateAccess()
 {
 OfferNumber number = new OfferNumber();
//Example for Delegate Inference
 number.totalDelegate += number_totalDelegate;
 }
int number_totalDelegate(int x, int y)
 {
 throw new NotImplementedException();
 }
 }

3. Using anonymous delegate,

Eg:
public class EventSampleAnonymousDelegate
 {
 public void DelegateAccess()
 {
 OfferNumber number = new OfferNumber();
//Example for Anonymous Delegate
 number.totalDelegate += delegate(int x, int y)
 {
 return x + y;
 };
 }
 }
4. Using Lamda Expression,
Eg:
public class EventSampleLamdaExpression
 {
 public void DelegateAccess()
 {
 OfferNumber number = new OfferNumber();
 //Example for using Lamda Expression
 number.totalDelegate += (x, y) =>
 {
 return x + y;
 };
 }
 }
Advertisements