[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 88
  • Last Modified:

Delegate in C#

Hi guys,

I just studied Delegate and understand that it encapsulate methods in "Invocation List".
And all the methods inside the invocation list will be called one by one.

My question is when do you use Delegate in real life scenarios?
I know that thread uses delegate. But beside that I heard that it's heavily used in Events.
Can you please show me actual "simple" examples that use delegate in a real life ?

Thanks~
0
Isabell
Asked:
Isabell
  • 2
1 Solution
 
anarki_jimbelCommented:
I believe you may find these examples/tutorials quite interesting:
https://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx
http://csharp-station.com/Tutorial/CSharp/Lesson14

Delegates are everywhere. They are very useful if you need, e.g., change, or add, or remove event handlers at run time.
LINQ uses delegates very intensively. Comparers, etc.
0
 
anarki_jimbelCommented:
Simple example:

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

namespace EventTesting
{
    public delegate void overdraftDelegate(object sender);

    class Program
    {
        static void Main(string[] args)
        {
            // Create three account
            Account a1 = new Account("a1", 1000, 100);
            Account a2 = new Account("a2", 1000, 100);
            Account a3 = new Account("a3", 1000, 100);
            // add a method that will handle "overdrafted" event - it's up to you what to do
            a1.Overdrafted += OverdraftHandler;
            a2.Overdrafted += OverdraftHandler;
            a3.Overdrafted += OverdraftHandler;
            //, make withdrawals and see what happens
            a1.Withdraw(1000);
            a2.Withdraw(1100);
            a3.Withdraw(1300);

            Console.ReadLine();
        }

        /// <summary>
        /// Our event handler that we are attaching to Account's event
        /// </summary>
        /// <param name="sender"></param>
        public static void OverdraftHandler(object sender)
        {
            // Cast sender to Account so that we are able to access it's properties
            Account a = (Account)sender;
            // Print info
            Console.WriteLine("Account '" + a.name + "' has overdraft!");
        }
    }


    /// <summary>
    /// Class account has name, balance and allowed overdraft.
    /// If we withdraw money - we want to know if overdraft happens.
    /// So we fire the event from the class.
    /// In the Prograsm class we add an event handler to handle this event. It simply prints the name of the account in our case.
    /// </summary>
    public class Account
    {
        public event overdraftDelegate Overdrafted;
        
        public Account(string _name, int _balance, int _allowedOverdraft)
        {
            this.name = _name;
            this.balance = _balance;
            this.allowedOverdraft = _allowedOverdraft;
        }
        public string name;

        int balance = 0;
        int allowedOverdraft = 0;

        public int Withdraw(int quantity)
        {
            int withdrawal = 0;

            if (quantity > (balance + allowedOverdraft))
            {
                withdrawal = balance + allowedOverdraft;
            }
            else
            {
                withdrawal = quantity;
            }
            balance -= withdrawal;
            if (balance < 0)
            {
                // fire event
                Overdrafted(this);
            }
            return withdrawal;
        }
    }
}

Open in new window

0
 
IsabellAuthor Commented:
Thanks!
0

Featured Post

Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now