locked
Delegates.... I just don't get it!! RRS feed

  • Question

  • Okay, I've just put some time to the side to learn some new c# stuff. 

    And at the height of ignorance, yet again, I find myself asking "why???!" when reading about the delegates.

    I still can't think of why they would actually simplify things, as every example I've read seem to mean MORE lines of code?

    I know they are definitely used with event handlers, but I'm still trying to get my head round why..


    Many thanks for your help... and patience!.. 
    Tuesday, February 24, 2009 3:18 PM

Answers

  •  You should look back twenty years or so and imagine that programming was for the most part linear. A program started at executable statement ONE and ended at executable statement 1000. Now there are still such programs but also many of them are interactive or more generally event driven. A user participates and throws the path of execution to another chunk of code in unpredictable way. A user therefore delegates the execution to this chunk of code which does its job and terminates its part only. Then the program waits for something else.

    Not only human users determine how the program will branch (nonlinearly). For instance some executions may require very long time and it is benefitial to run them in the background while the user or the program will do something else. How can you do it? Even without knowing much about programming, simply thinking in logical blocks, you can come up with an idea that you need to delegate this task to another thread and run it in the background. Therefore you will need a delegate for it. So what? That background process will finish and you will never know what happened unless that delegate calls a special method: CallBack function that will tell the main thread that it finished and perhaps sent some results. Complex environment means complex designs and delegates make it feasible and practical.

    AlexB
    Tuesday, February 24, 2009 3:35 PM

All replies

  • For event handling cases, c# delegate concept is much simpler than Java's interface sinking concept.
    delegate is also useful for asynchronous programming.

    Happy programming .net
    Tuesday, February 24, 2009 3:27 PM
  • An automobile contains far more parts than a horse-drawn wagon.  Which is better?
    Mark the best replies as answers. "Fooling computers since 1971."
    Tuesday, February 24, 2009 3:28 PM
  • If there's no gas available but lots of grass, the horse cart would be better *grin*
    http://blog.voidnish.com
    Tuesday, February 24, 2009 3:32 PM
  • aikidojo said:

    Okay, I've just put some time to the side to learn some new c# stuff. 

    And at the height of ignorance, yet again, I find myself asking "why???!" when reading about the delegates.

    I still can't think of why they would actually simplify things, as every example I've read seem to mean MORE lines of code?

    I know they are definitely used with event handlers, but I'm still trying to get my head round why..


    Many thanks for your help... and patience!.. 


    When you say more lines of code, can you give an example? And also post how you'd have written it with fewer lines of code had you avoided delegates.

    http://blog.voidnish.com
    Tuesday, February 24, 2009 3:33 PM
  •  You should look back twenty years or so and imagine that programming was for the most part linear. A program started at executable statement ONE and ended at executable statement 1000. Now there are still such programs but also many of them are interactive or more generally event driven. A user participates and throws the path of execution to another chunk of code in unpredictable way. A user therefore delegates the execution to this chunk of code which does its job and terminates its part only. Then the program waits for something else.

    Not only human users determine how the program will branch (nonlinearly). For instance some executions may require very long time and it is benefitial to run them in the background while the user or the program will do something else. How can you do it? Even without knowing much about programming, simply thinking in logical blocks, you can come up with an idea that you need to delegate this task to another thread and run it in the background. Therefore you will need a delegate for it. So what? That background process will finish and you will never know what happened unless that delegate calls a special method: CallBack function that will tell the main thread that it finished and perhaps sent some results. Complex environment means complex designs and delegates make it feasible and practical.

    AlexB
    Tuesday, February 24, 2009 3:35 PM
  • Thanks for all your comments guys.

    Maybe the problem is the examples I've read on the MSDN help are too simplified and therefore would not in real cases justify using a delegate.

    Maybe when I get the part in my project that I need to run stuff in the background it will make more sense.


    Thanks again guys
    Tuesday, February 24, 2009 3:41 PM
  • Oh and to Nishant,

    I'm still way too much of a newbie to know how I would have written it yet :o)

    Thanks for your help
    Tuesday, February 24, 2009 3:43 PM
  • Here is a basic example of an event which is nothing more then a delegate.

    Subscribing to an Event

    Think of a delegate as an object oriented method pointer.

    .Net C# Delegates and Events

    Also read when you have time:

    C# Event Implementation Fundamentals, Best Practices and Conventions

    Delegates And Events - The Uncensored Story - Part 1
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Tuesday, February 24, 2009 5:50 PM
  • I’m also not familiar with delegates but here’s what I’ve got so far:

    namespace DelegateTest01

    {

    public partial class Form2 : Form

     

    {

    public delegate void MyFirstDelegate(String myMessage);

    public static event MyFirstDelegate MyOwnEvent;

    public Form2()

    {

    InitializeComponent();

    }

    private void Form2_Load(object sender, EventArgs e)

    {

    String message = "cool!!";

    MyOwnEvent += new MyFirstDelegate(MyDelegateIsActive);

    MyOwnEvent(message);

    }

    public static void MyDelegateIsActive(String myMessage)

    {

    MessageBox.Show(myMessage);

    }

    }

    }

    Tuesday, February 24, 2009 7:54 PM
  • Go over my example in the hyperlink "Subscribing to an Event" as it is almost exactly what you are attempting to do. I think you are "getting" it which is good news...
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Tuesday, February 24, 2009 8:00 PM
  • I put questions I still have concerning delegates in the comments with a ?? next to it. I must be dumb or something but I don't understand how this works, when is a typical time to use it in a web application and more importantly why I need. I've read each of the linked articles and all I can say is I am dense. Please have patience with me.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace MJM.Examples
    {
    // public delegate returning nothing called NewsDelegate
    // and accepts an object called news of type News
    public delegate void NewsDelegate(News news);
    // public class called News has a property called news.
    public class News
    {
    // property of News
    public string news;
    // Constructor for News
    public News(string news)
    {
    // assigns input news to news property
    this.news = news;
    }
    }
    // public class called NewsService
    public class NewsService
    {
    // ?? public event Not sure how this works ??
    public event NewsDelegate NewsEventSubScribers;
    // public method called newNews returning nothing input string called news
    public void newNews(string news)
    {
    Console.WriteLine("Event New News");
    // ?? Not sure what this means either ?? if there are event subscribers?
    if (NewsEventSubScribers != null)
    {
    // ?? Nor this. ??
    NewsEventSubScribers(new News(news));
    }
    }
    //public constructor for News Service
    public NewsService() { }
    }
    // public class called subscriber
    public class Subscriber
    {
    // public string called name
    public string name;
    // ?? Not sure what to call this, delegate instance or class, maybe ??
    NewsDelegate delNews;
    // method to subscribe to a news service
    public void SubscribeNewsService(NewsService ns)
    {
    // ?? instance of NewsDelegate calling WriteNews method Don't understand... ??
    delNews = new NewsDelegate(WriteNews2);
    // ?? gives me heartburn makes me feel dumb
    ns.NewsEventSubScribers += delNews;
    // Write out to the console
    Console.WriteLine(name + " subscribed to news");
    }
    // method to unsubscribe from a news service
    public void UnsubscribeNewsService(NewsService ns)
    {
    // ?? 1st time I've ever seen -=
    ns.NewsEventSubScribers -= delNews;
    // Write out to the console
    Console.WriteLine(name + " unsubscribed to news");
    }
    // method to write news takes news as parameter
    public void WriteNews(News e)
    {
    // Write out to the console
    Console.WriteLine(name + " recieved news: " + e.news);
    }
    // method to write news takes news as parameter
    public void WriteNews2(News e)
    {
    // Write out to the console
    Console.WriteLine(name + " recieved news 2: " + e.news);
    }
    // public constructor for Subscriber creates an
    // instances of subscriber setting the name property
    public Subscriber(string name)
    {
    this.name = name;
    }
    }
    class MakeNews
    {
    // main method
    static void Main(string[] args)
    {
    // create a newsservice
    NewsService ns = new NewsService();
    // create a subscriber
    Subscriber julie = new Subscriber("Julie");
    // ?? Subscribe to news service but not sure how this works ??
    julie.SubscribeNewsService(ns);
    // ?? call newNews method and trigger the WriteNews method somehow ??
    ns.newNews("Test Test Test");
    }
    }
    }

    Mike M
    Mike M
    Tuesday, February 24, 2009 8:47 PM
  • Are you trying to do the Observer Design Pattern or just have a class that has an event associated with it? Here is a basic event driven program here:

    I would change my delegate as follows:

    public delegate void NewsDelegate(string news);

     
        public class NewsService  
        {  
            //This class is broadcasting the event  
            public event NewsDelegate NewsEvent;  
            public NewsService() { }  
     
            /*It is good prractice to have a   
              protected virtual method that will  
              fire the event. This will only get  
              get launched privately  
            */  
            protected virtual void OnNewsEvent(string news)  
            {        
                if (NewsEvent != null)                            
                    NewsEvent(news);              
            }  
     
            //This will fire the event  
            public void TestEvent(string news)  
            {  
                OnNewsEvent(news);  
            }  
        } 



    To test your class:

     class MakeNews  
        {  
            // main method    
            static void Main(string[] args)  
            {  
                NewsService newsService = new NewsService();  
                newsService.NewsEvent += new NewsDelegate(newsServive_NewsEvent);  
                newsService.TestEvent("Superman Returns");  
                Console.ReadLine();  
            }  
     
            static void newsServive_NewsEvent(string news)  
            {  
                Console.WriteLine(news);  
            }          
        } 

    If you want to see an example of the Observer see here


    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    • Edited by JohnGrove Tuesday, February 24, 2009 10:54 PM edit
    Tuesday, February 24, 2009 10:51 PM