Using C# Delegates with Events


.NET Delegates are objects which can refer to static and instance methods in memory at runtime and can call those methods in your program. In this tutorial I will show you how you can create and use delegates in C#.

To explain delegates and their use in real world programs I am creating a BankAccount class in which I will declare one delegate using C# delegate keywork.

public class BankAccount
{
    int amount = 0; 
    // Declare Delegate Type Object
    public delegate void BankDelegate(int oldBalance, int newBalance); 
    // Create Delegate Type Events 
    public event BankDelegate OnDeposit;
    public event BankDelegate OnWithdraw; 
    public void Deposit(int a)
    {
        // Fire OnDeposit Event and pass old and new balance amount
        OnDeposit(this.amount, this.amount + a);         

        this.amount += a;         

    } 
    public void Withdraw(int a)
    {
        // Fire OnWithdraw Event and pass old and new balance amount
        OnWithdraw(this.amount, this.amount - a);
        
        this.amount -= a;
    }
} 

To test BankAccount class create one Windows Form Application using C# and in the Form Load event create object of BankAccount class as shown below

Bank Applicatioin using Delegates and Events

// Declare BankAccount class variable 
BankAccount account = null;
 
private void Form1_Load(object sender, EventArgs e)
{
    account = new BankAccount();
     
   // Attach Event Handlers with Events
   account.OnDeposit += new BankAccount.BankDelegate(account_OnDeposit);
   account.OnWithdraw += new BankAccount.BankDelegate(account_OnWithdraw);
} 

Following code is calling BankAccount class methods on Deposit and Withdraw button click events.

private void btnDeposit_Click(object sender, EventArgs e)
{
    account.Deposit(Int32.Parse(textBox1.Text)); 
}

private void btnWithdraw_Click(object sender, EventArgs e)
{
    account.Withdraw(Int32.Parse(textBox1.Text)); 
}

Following methods are event handlers methods attached with delegate type events OnDeposit and OnWithdraw

void account_OnDeposit(int oldBalance, int newBalance)
{
    label4.Text = oldBalance.ToString();
    label5.Text = newBalance.ToString(); 
}

void account_OnWithdraw(int oldBalance, int newBalance)
{
    label4.Text = oldBalance.ToString();
    label5.Text = newBalance.ToString(); 
} 

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments