Solved

Delegate in C#

Posted on 2016-09-11
3
47 Views
Last Modified: 2016-09-13
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
Comment
Question by:Isabell
  • 2
3 Comments
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 41793549
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
 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 500 total points
ID: 41793563
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
 

Author Closing Comment

by:Isabell
ID: 41797067
Thanks!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now