Skip to content

Instantly share code, notes, and snippets.

@SridharPasham
Created August 4, 2015 13:13
Show Gist options
  • Save SridharPasham/0d87c774aed443fd8d6c to your computer and use it in GitHub Desktop.
Save SridharPasham/0d87c774aed443fd8d6c to your computer and use it in GitHub Desktop.
using System;
namespace ConsoleApplication1
{
// Declare delegate
public delegate int mathDelegate(int a, int ab);
class EventDelegateClass
{
// event of type mathDelegate
public event mathDelegate mathEvenHandler;
public int Sum(int x, int y)
{
var s = x + y;
if (s > 5)
{
// check for any event listeners subscribed.
if (mathEvenHandler != null)
{
// call the event listener.
mathEvenHandler.Invoke(4, 5);
}
}
return s;
}
public int Multiply(int a, int b)
{
var s = a * b;
return s;
}
}
class Test
{
static void Main(string[] args)
{
EventDelegateClass edOjb = new EventDelegateClass();
// subscribe to event
edOjb.mathEvenHandler += EventListener;
// Create delegate
mathDelegate delObj = null;
// point method to delegate (Multicast).
delObj += edOjb.Sum;
delObj += edOjb.Multiply;
// Invoke delegate
var result = delObj.Invoke(2, 4);
// the result is the value of last call
Console.WriteLine("Delegate call result: "+result);
Console.ReadLine();
}
static int EventListener(int p, int q)
{
var temp = p + q;
Console.WriteLine("Sum in event listener: " + temp);
return temp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment