Solved

Delegate in C#

Posted on 2016-09-11
3
73 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 30

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 30

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

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

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

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

726 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