tags:

views:

893

answers:

12

I think I understand the concept of a delegate in C# as a pointer to a method, but I cant find any good examples of where it would be a good idea to use them. What are some examples that are either significantly more elegant/better with delegates or cant be solved using other methods?

+5  A: 

I primarily use the for easy asynch programming. Kicking off a method using a delegates Begin... method is really easy if you want to fire and forget.

A delegate can also be used like an interface when interfaces are not available. E.g. calling methods from COM classes, external .Net classes etc.

ck
A: 

there isn't really anything delgates will solve that can't be solved with other methods, but they provide a more elegant solution.

With delegates, any function can be used as long as it has the required parameters.

The alternative is often to use a kind of custom built event system in the program, creating extra work and more areas for bugs to creep in

Jroc
+10  A: 

The .NET 1.0 delegates:

this.myButton.Click += new EventHandler(this.MyMethod);

The .NET 2.0 delegates:

this.myOtherButton.Click += delegate {
    var res = PerformSomeAction();
    if(res > 5)
        PerformSomeOtherAction();
};

They seem pretty useful. How about:

new Thread(new ThreadStart(delegate {
    // do some worker-thread processing
})).Start();
Justice
+4  A: 

Events are the most obvious example. Compare how the observer pattern is implemented in Java (interfaces) and C# (delegates).

Also, a whole lot of the new C# 3 features (for example lambda expressions) are based on delegates and simplify their usage even further.

petr k.
+2  A: 

For example in multithread apps. If you want several threads to use some control, You shoul use delegates. Sorry, the code is in VisualBasic.

Firts you declare a delegate

Private Delegate Sub ButtonInvoke(ByVal enabled As Boolean)

Write a fucntion to enable/disable button from several threads

Private Sub enable_button(ByVal enabled As Boolean)
    If Me.ButtonConnect.InvokeRequired Then

        Dim del As New ButtonInvoke(AddressOf enable_button)
        Me.ButtonConnect.Invoke(del, New Object() {enabled})
    Else
        ButtonConnect.Enabled = enabled
    End If

End Sub
Roman Shestakov
+2  A: 

I use them all the time with LINQ, especially with lambda expressions, to provide a function to evaluate a condition or return a selection. Also use them to provide a function that will compare two items for sorting. This latter is important for generic collections where the default sorting may or may not be appropriate.

   var query = collection.Where( c => c.Kind == ChosenKind )
                         .Select( c => new { Name = c.Name, Value = c.Value } )
                         .OrderBy( (a,b) => a.Name.CompareTo( b.Name ) );
tvanfosson
+2  A: 

One of the benefits of Delegates is in asynchronous execution.

when you call a method asynchronously you do not know when it will finish executing, so you need to pass a delegate to that method that point to another method that will be called when the first method has completed execution. In the second method you can write some code that inform you the execution has completed.

Marwan Aouida
+1  A: 

Some other comments touched on the async world... but I'll comment anyway since my favorite 'flavor' of doing such has been mentioned:

ThreadPool.QueueUserWorkItem(delegate
{
    // This code will run on it's own thread!
});

Also, a huge reason for delegates is for "CallBacks". Let's say I make a bit of functionality (asynchronously), and you want me to call some method (let's say "AlertWhenDone")... you could pass in a "delegate" to your method as follows:

TimmysSpecialClass.DoSomethingCool(this.AlertWhenDone);
Timothy Khouri
+1  A: 

Outside of their role in events, which your probably familiar with if you've used winforms or asp.net, delegates are useful for making classes more flexible (e.g. the way they're used in LINQ).

Flexibility for "Finding" things is pretty common. You have a collection of things, and you want to provide a way to find things. Rather than guessing each way that someone might want to find things, you can now allow the caller to provide the algorithm so that they can search your collection however they see fit.

Here's a trivial code sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delegates
{
    class Program
    {
        static void Main(string[] args)
        {
            Collection coll = new Collection(5);
            coll[0] = "This";
            coll[1] = "is";
            coll[2] = "a";
            coll[3] = "test";

            var result = coll.Find(x => x == "is");

            Console.WriteLine(result);

            result = coll.Find(x => x.StartsWith("te"));

            Console.WriteLine(result);

    }

}

public class Collection
{
    string[] _Items;

    public delegate bool FindDelegate(string FindParam);

    public Collection(int Size)
    {
        _Items = new string[Size];

    }

    public string this[int i]
    {
        get { return _Items[i]; }
        set { _Items[i] = value; }
    }

    public string Find(FindDelegate findDelegate)
    {
        foreach (string s in _Items)
        {
            if (findDelegate(s))
                return s;
        }
        return null;
    }

}
}

Output

is

test

Giovanni Galbo
+7  A: 

What exactly do you mean by delegates? Here are two ways in which they can be used:

void Foo(Func<int, string> f) {
 //do stuff
 string s = f(42);
 // do more stuff
}

and

void Bar() {
 Func<int, string> f = delegate(i) { return i.ToString(); } 
//do stuff
 string s = f(42);
 // do more stuff
}

The point in the second one is that you can declare new functions on the fly, as delegates. This can be largely replaced by lambda expressions,and is useful any time you have a small piece of logic you want to 1) pass to another function, or 2) just execute repeatedly. LINQ is a good example. Every LINQ function takes a lambda expression as its argument, specifying the behavior. For example, if you have a List<int> l then l.Select(x=>(x.ToString()) will call ToString() on every element in the list. And the lambda expression I wrote is implemented as a delegate.

The first case shows how Select might be implemented. You take a delegate as your argument, and then you call it when needed. This allows the caller to customize the behavior of the function. Taking Select() as an example again, the function itself guarantees that the delegate you pass to it will be called on every element in the list, and the output of each will be returned. What that delegate actually does is up to you. That makes it an amazingly flexible and general function.

Of course, they're also used for subscribing to events. In a nutshell, delegates allow you to reference functions, using them as argument in function calls, assigning them to variables and whatever else you like to do.

jalf
A: 

Thanks for all the excellent replies. I've given jalf the answer because his description was the best.

I havent done much GUI or async development so I now see what delegates can bring to the table.

Alex
+2  A: 

Technically delegate is a reference type used to encapsulate a method with a specific signature and return type