Friday, November 30, 2018

Understanding Events in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class TransactionEventArgs : EventArgs
{
    private int _transactionAmount;
    // "Credited": deposit
    // "Debited" : withdraw
    private string _transactionType;
    public TransactionEventArgs(int amt, string type)
    {
        this._transactionAmount = amt;
        this._transactionType = type;
    }
    public int TranactionAmount
    {
        get
        {
            return _transactionAmount;
        }
    }
    public string TranactionType
    {
        get
        {
            return _transactionType;
        }
    }
}

/*like:
public delegate void EventHandler(object sender, EventArgs e);

*/
public delegate void TransactionHandler(object sender, TransactionEventArgs e);
class Account
{
    //like:
    //public event EventHandler Click;
    //
    //the TransactionMade event and its TransactionHandler delegate(s)
    public event TransactionHandler TransactionMade; // Event Definition
    public int BalanceAmount;
    public Account(int amount)
    {
        this.BalanceAmount = amount;
    }
    //publisher invokes a event
    public void Debit(int debitAmount)
    {
        if (debitAmount < BalanceAmount)
        {
            BalanceAmount = BalanceAmount - debitAmount;
            TransactionEventArgs e = new TransactionEventArgs(debitAmount, "Debited");
            OnTransactionMade(e); // Debit transaction made
        }
    }

    public void Credit(int creditAmount)
    {
        BalanceAmount = BalanceAmount + creditAmount;
        TransactionEventArgs e = new TransactionEventArgs(creditAmount, "Credited");
        OnTransactionMade(e); // Credit transaction made
    }
    protected virtual void OnTransactionMade(TransactionEventArgs e)
    {
        if (TransactionMade != null)
        {
            TransactionMade(this, e); // Raise the event
        }
    }
}

class TestMyEvent
{
    private static void SendNotification(object sender, TransactionEventArgs e)
    {
        Console.WriteLine(
            "Your Account is {0} for ${1} ",
            e.TranactionType,
            e.TranactionAmount);
    }
    private static void Main()
    {
        Account MyAccount = new Account(10000);
        //like: this.button1.Click += new System.EventHandler(this.button1_Click);
        //
        //note: the += operator of event will subscribe the event append a delegate
        MyAccount.TransactionMade += new TransactionHandler(SendNotification);
        MyAccount.Credit(500);
        Console.WriteLine("Your Current Balance is : " + MyAccount.BalanceAmount);
        Console.ReadLine();
    }
}