A simple Event Handling with Delegate Example
A simple Event Handling Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace ManualResetEvent_
{
// A delegate definition for handling the event . They are like binders linking the event and the handler
public delegate void transactionhandler (object sender, transactionArgs e);
public class transactionArgs : EventArgs
{
public int Transactionamt {get;set;}
public string Transactiontype {get;set;}
public transactionArgs(int amt,string type)
{
Transactionamt=amt;
Transactiontype=type;
}
}
//Publisher of the eevent contains definition of the event of type delegate
public class Account
{
public event transactionhandler transactionMadeEvent; //Creating an Event of type the handler
public int BalanceAmt;
public Account(int amt)
{
BalanceAmt = amt;
}
protected virtual void OnTransactionMade(transactionArgs args)
{
if (transactionMadeEvent != null)
{
transactionMadeEvent(this, args);
}
}
public void Debit(int debitAmount)
{
if (BalanceAmt > debitAmount)
{
BalanceAmt = BalanceAmt - debitAmount;
transactionArgs args_ = new transactionArgs(debitAmount, "Debit");
OnTransactionMade(args_);
}
}
public void Credit(int creditAmount)
{
BalanceAmt = BalanceAmt + creditAmount;
transactionArgs args_1 = new transactionArgs(creditAmount, "Credit");
OnTransactionMade(args_1);
}
}
//Subscriber of the event
class TestEvent
{
private static void EventHandler(Object sender, transactionArgs e) // the handlers for the event
{
Console.WriteLine("Account is {0} for {1} dollars", e.Transactiontype, e.Transactionamt);
}
private static void SendMessage(Object sender, EventArgs e) // the handlers for the event
{
Console.WriteLine("SMS sent to you mobile");
}
public static void Main()
{
Account acct = new Account(1000);
acct.transactionMadeEvent += new transactionhandler(EventHandler); //Event is linked to the handler via delegate
acct.transactionMadeEvent += new transactionhandler(SendMessage); //Event is linked to the handler via delegate
acct.Credit(500); //When this method is called it will raise the event which is always declared inside a protected virtual method
Console.WriteLine("Your Current Balance" + acct.BalanceAmt);
Console.ReadLine();
}
}
}
Comments
Post a Comment