MainClass
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EventsAndDelegates
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/*
Events are used to Get notify when a specific task is completed. Then we can call our functions.
Due to events, we are never required to edit our class which contains a specific code
*/
private void Form1_Load(object sender, EventArgs e)
{
// Create Object of a class
Calculator mCalculator = new Calculator();
// Adding a subscriber
/*
* All the method we add to this event will be triggered when the function 'AddNum' execution is completed
* For this example we want to trigger SendEmail and SendMessage. So these methods will be triggered
* If we do not use events and delegates, then we need to add these methods AddNum function to Calculator class
* Which could cause some problems. So this is the bes way
*/
mCalculator.NumberAdded += SendEmail;
mCalculator.NumberAdded += SendMessage;
// Call AddNum function in Calculator class
mCalculator.AddNum(5, 10);
}
// Method to send email
private void SendEmail(int result) {
MessageBox.Show(String.Format("Result is: {0}. Sending Email", result));
}
// Method to send messaage
private void SendMessage(int result)
{
MessageBox.Show(String.Format("Result is: {0}. Sending Message", result));
}
}
}
Calculator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventsAndDelegates
{
class Calculator
{
// Create a delegate with one parameter 'result'
public delegate void CalculatorEventHandler(int result);
// Create an event for that delegate
public event CalculatorEventHandler NumberAdded;
// Write a function to add two numbers
public void AddNum(int num1, int num2)
{
int result = num1 + num2;
// After addition, call OnResult
OnResult(result);
}
protected virtual void OnResult(int result)
{
// This methods checks, if there are any subscribers for this events
// If true, it fires event and all methods subscribed to this event gets executed
if (NumberAdded != null)
NumberAdded(result);
}
}
}
No comments