tags:

views:

225

answers:

5

I've been searching the Web, including MSDN.com for a easy-to-understand explanation of delegates in c#. There's plenty of tutorials/lessons...but its a hard concept for me to grasp. So i thought I'd ask fellow programmers. Can anyone explain?

+5  A: 

Delegates are like function pointers.

Take a look at this

using System;

namespace Akadia.BasicDelegate
{
    // Declaration
    public delegate void SimpleDelegate();

    class TestDelegate
    {
        public static void MyFunc()
        {
            Console.WriteLine("I was called by delegate ...");
        }

        public static void Main()
        {
            // Instantiation-- we set this simpleDelegate to MyFunc
            SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);

            // Invocation-- MyFunc is called. 
            simpleDelegate();
        }
    }
}

So what happens is that when you call simpleDelegate, MyFunc is called instead, because simpleDelegate is pointing to MyFunc.

In the case of doubt, you should copy the above code, paste it inside your VS, and run your debugger through it. Examine how the program flows from one place to another; see for yourself after simpleDelegate() line is called, the program jumps to MyFunc and executes from there. Examine the simpleDelegate variable, see that it contains a reference to MyFunc the method. This would be the best way for you to get familiar with the whole delegate thing.

Ngu Soon Hui
It's actually (quite) a bit more complicated than that; but I like "delegates are just function pointers".
Dan
Like a function pointer but only better. You can't invoke an unassigned delegate, and I think they support function overloading too.
Swanny
They don't support function overloading in a sense that you cannot get a delegate that's bound to a method group, and will call one of several methods depending on types of arguments you pass to it.
Pavel Minaev
A: 

For a good tutorial, please see Delegates:

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value, as in this example:

Andrew Hare
A: 

Think Functors. i.e. a function that can be handled sort of like an object (i.e. a pointer)

Oren Mazor
I.e., in order for him to understand what delegates are, you suggest that he first learn what "functor", "object" and "pointer" are?
Pavel Minaev
that's a fair point. I knew what functors were before I ever heard of delegates. the former helped understand what the latter was.
Oren Mazor
+1  A: 

Basically a delegate runs any number of methods you subscribe to it. They must match the parameters and the return type (this is called "signature"), that is, if your delegate takes two ints and returns a void:

public delegate void MyDelegate(int i1, int i2);

The methods you subscribe to it must take two strings and return a void too:

public void Add(int int1, int int2)
{
    MessageBox.Show((int1 + int2).ToString());
}

public void Multiply(int int1, int int2)
{
    MessageBox.Show((int1 * int2).ToString());
}

And now subscribe, run and see the results:

public void SubscribeAndRun()
{
    MyDelegate d = new MyDelegate(Add);

    d += Multiply;

    d.Invoke(2, 3);
}

Delegates are extensively used to call other methods when an event happens. In C# events are delegates encapsulated to use add and remove (to add or remove the methods the event will run when it fires).

Carlo
A: 

Here's a simple example

using System;

namespace delegates
{
    class Program
    {
        // An event which you set up by attaching handlers (delegates)
        // and then running using the Invoke() method.
        private EventHandler<EventArgs> _event;

        void SetupFoo()
        {
            // Attach the function foo to the _event
            _event += Foo;
        }

        void SetupBar()
        {
            // Attach a delegate (aka anonymous method) to the _event
            _event += delegate { Console.WriteLine("Bar is called"); };
        }

        void SetupBaz()
        {
            // Attach a lambda to the _event
            _event += (sender, e) => Console.WriteLine("Baz is called");
        }

        void Fire()
        {
            // Run all the attached methods/delegates/lambdas
            _event.Invoke(this, EventArgs.Empty); 
        }


        static void Main(string[] args)
        {
            var prog = new Program();
            prog.SetupFoo();
            prog.SetupBar();
            prog.SetupBaz();
            prog.Fire();
            Console.ReadKey();
        }

        private static void Foo(object sender, EventArgs e)
        {
            Console.WriteLine("Foo is called");
        }
    }
}

This produces the output:

Foo is called
Bar is called
Baz is called

Why are delegates important? Because Fire() was responsible only for the timing of the event execution, but other functions were responsible for the consequences of the event. These consequences are expressed as delegates.

Phillip Ngan