namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
Account MyAccount = new Account(10000);
subscriber Mysubscriber = new subscriber();
public Form1()
{
InitializeComponent();
MyAccount.TransactionMade += new TransactionHandler(Mysubscriber.SendNotification);
}
private void ButtonCredit(object sender, EventArgs e)
{
MyAccount.Credit(500);
MessageBox.Show("your current balance is ", MyAccount.BalanceAmount.ToString());
}
}
}
namespace WindowsFormsApp1
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public delegate void TransactionHandler(object sender, TransactionEventArgs e);
class Account
{
public event TransactionHandler TransactionMade;
public int BalanceAmount;
public Account(int amount)
{
this.BalanceAmount = amount;
}
public void Debit(int debitAmount)
{
if (debitAmount < BalanceAmount)
{
BalanceAmount = BalanceAmount - debitAmount;
TransactionEventArgs e = new TransactionEventArgs(debitAmount, "Debited");
OnTransactionMade(e);
}
}
public void Credit(int creditAmount)
{
BalanceAmount = BalanceAmount + creditAmount;
TransactionEventArgs e = new TransactionEventArgs(creditAmount, "Credited");
OnTransactionMade(e);
}
protected virtual void OnTransactionMade(TransactionEventArgs e)
{
if (TransactionMade != null)
{
TransactionMade(this, e);
}
}
}
public class TransactionEventArgs : EventArgs
{
public int TranactionAmount { get; set; }
public string TranactionType { get; set; }
public TransactionEventArgs(int amt, string type)
{
TranactionAmount = amt;
TranactionType = type;
}
}
public class subscriber
{
public void SendNotification(object sender, TransactionEventArgs e)
{
MessageBox.Show(e.TranactionType);
MessageBox.Show(e.TranactionAmount.ToString());
}
}
}
What I have tried:
this is console example i found. i try to make it to a winform. not sure whether i put the position right.
1. is it good practice to create MyAccount in that position? inside partial Class Form1, or should i put it in Class program Main()?
2. good to put event subscription in Form1()?
3. is it necessary to put unsubscription , where if needed?
learning Event! thank you!