Solved

Delegate in C#

Posted on 2016-09-11
3
54 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

920 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

11 Experts available now in Live!

Get 1:1 Help Now