.NET General

Moderators: None (Apply to moderate this forum)
Number of threads: 797
Number of posts: 1359

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Why use delegates? Posted by BobLewiston on 26 Feb 2009 at 4:37 PM
Why use delegates?

I understand HOW to use delegates, but in what situations would you actually use them? The examples I see in the literature are all in situations where the code could just be written without ever using them.

Report
Re: Why use delegates? Posted by secutos on 16 Mar 2009 at 3:36 PM
Delegates are extremely useful in multithreading and cross-thread operations. If you try accessing a Button control on a Windows Form created on Thread 1 by Thread 2, you'll get a nice yellow error telling you "This button cannot be accessed from a thread other than which it was created on." In that case, you would use delegates to play with the button.
Report
Re: Why use delegates? Posted by Psightoplazm on 24 Apr 2009 at 3:38 PM
There are seriously too many usefull situations to apply the usage of delegates to go and list them off -

I would say these are at the top of the usefulness list:

Creating a custom scope - so lets say you want to apply a method/action to a list of objects and apply locally scoped values into the body of the delegate but really don't need to add a bunch of additional variables to the scope of the entire class...

        [STAThread]
        public static void Main()
        {
            // Creating a custom window...
            var win = new Form();
            // opening an xml file...
            var doc = new XmlDocument();
            doc.Load("C:\\MyDoc.xml");
            var root = doc.DocumentElement;

            //Cycling through each of the nodes in the root element of the XML file
            foreach (var child in root.ChildNodes.Cast<XmlElement>())
            {
                // Creating a reference to the node 
                var node = child; 
                var name = node.GetAttribute("name");
                // Creating a new button
                var button = new Button()
                                 {
                                     Dock = DockStyle.Top,
                                     Text = name
                                 };

                // Giving the button's click handler a delegate that has access to
                // the node that is associated with this itteration of the foreach
                // loop. This would be difficult using an externally defined method
                button.Click +=
                    delegate
                        {
                            var message = node.GetAttribute("message");
                            MessageBox.Show("The node named " + name + " had the message:\r\n" + message);
                            //Obviously you won't often be creating buttons like this - but you could very
                            //easily add actions to the Tags of a tree node or a custom class of your own.
                        };

                // adding the button to the form
                win.Controls.Add(button);
            }

            // showing the completed dynamic window
            win.ShowDialog();
        }


    }


also - when used properly - delegates can make huge reductions in your code. Take for example this generic filter...

    public class GenericObjectFilter
    {
        public TItem[] FilterObjects<TItem>(TItem[] items, Func<TItem, string> identifier, string[] include)
        {
            var results = new List<TItem>();
            foreach (var item in items)
                if (include.Contains(identifier(item)))
                    results.Add(item);
            return results.ToArray();
        }
    }



This one filter can be used to filter literally any object in existence...

public class SomeClassA
{
    public string ClassAName { get; set; }
}
public class SomeClassB
{
    public string ClassBName { get; set; }
}
public class SomeClassC
{
    public string ClassCName { get; set; }
}

    static class Program
    {
        [STAThread]
        public static void Main()
        {
            var filterStrings = new[] {"Aardvark", "Video", "Game"};

            var collectionA = new SomeClassA[100];
            var collectionB = new SomeClassB[100];
            var collectionC = new SomeClassC[100];

            var filter = new GenericObjectFilter();

            var filteredA = filter.FilterObjects(
                collectionA,
                item => item.ClassAName,
                filterStrings);

            var filteredB = filter.FilterObjects(
                collectionB,
                item => item.ClassBName,
                filterStrings);

            var filteredC = filter.FilterObjects(
                collectionC,
                item => item.ClassCName,
                filterStrings);

            // You now have filtered collections of 3 totally different object type collections
            // and you only ever wrote one single filter.
        }

    }




So let's say the filter you wrote was like 200 lines of code long... and you had to access three differing parts of the object you are filtering - without a delegate to tell the filter method how to grab the information it needs, you would actually have to write 3 different copies of the same exact filter - or 100 different copies if you had 100 different item types to filter.

but this way you can stick this filter in a DLL somewhere along with a bunch of other usefull stuff and just use it whenever you need it.


anyways - that's just a couple of uses - Once you start using them I garauntee you will find hundreds of uses for them.

></\/~Psightoplasm`~
Report
Re: Why use delegates? Posted by spickersgill on 6 Jun 2009 at 10:53 AM
Please check out my blog post (Delegates Explained in Plain English ) for what I hope you will find to be a clear explanation of delegates and what they provide.

Regards

Simon
Report
Re: Why use delegates? Posted by AsmGuru62 on 8 Jun 2009 at 4:51 AM
Nice job, Simon!
Do you have anything more to read on .NET?
Report
Re: Why use delegates? Posted by spickersgill on 8 Jun 2009 at 12:00 PM
That was my first post. I'm currently writing an introduction to Object Oriented Programming techniques. Keep a look out for it.



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.