Solved

Delegate in C#

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

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
C# Windows app updating JSON file error. 9 39
Header Font Size in Grid View 6 27
Need help with another query 10 39
Need to find a web event on the IIS server 4 10
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…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

733 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