tags:

views:

190

answers:

3
+3  Q: 

Delegates in C#

Hello guys.

I`m having some trouble to understand why does a delegate works. I have many code examples, but i still could not grasp it properly.

Can someone explain it to me in "plain english"? Of course, examples of code will help, but i think i need more of a description of how/why it works.

EDIT:

Well, the question is: why does delegates work? What is a "flow chart" of the entire process?

What are the pre-requisites of using delegates?

I hope this makes the question clearer, thanks.

THanks

+1  A: 

Its an inversion principle. Normally, you write code that calls a method and the method you call is known at the time that you write the code. Delegates allow you to anonymously invoke methods. That is you do not know the actual method that is called when the program is running.

It is useful in separating the concerns of different parts of an application. So you can have some code that performs tasks on a data store. You may have other code that processes the data. The processes on the data need not know the structure of the data store and the data store should not be dependant on the uses of the data.

The processing code can be written assuming certain things about the data that are independant of the structure of the data store. That way, we can change the structure of the data store with less worry about affecting the processes on the data.

Vincent Ramdhanie
+3  A: 

One way to think about a delegate is like a reference to a function. For example, say you have a button in a window, and you want something to happen when the button is clicked. You can attach a delegate to the Click event of the button, and whenever the user clicks this button, your function will be executed.

class MyWindow : Window
{
    Button _button;

    public MyWindow()
    {
        _button = new Button();
        // place the button in the window
        _button.Click += MyWindow.ButtonClicked;
    }

    static void ButtonClicked(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Button Clicked");
    }
}

Notice how I make ButtonClicked a static function - I want to make a point about non-static functions next. Suppose instead that ButtonClicked is a non-static member:

class MyWindow : Window
{
    Button _button;
    int _numClicked = 0;

    public MyWindow()
    {
        this._button = new Button();
        // place the button in the window
        this._button.Click += this.ButtonClicked;
    }

    void ButtonClicked(object sender, RoutedEventArgs e)
    {
        this._numClicked += 1;
        MessageBox.Show("Button Clicked " + this._numClicked + " times");
    }
}

Now the delegate contains both a reference to the function "ButtonClicked" and the instance, "this", which the method is called on. The instance "this" in the MyWindow constructor and "this" in ButtonClicked are the same.

This is a specific case of a concept known as closures which allows "saving" the state - the current object, local variables, etc. - when creating a delegate. In the above example, we used "this" from the constructor in the delegate. We can do more than that:

class MyWindow : Window
{
    Button _button;
    int _numClicked = 0;

    public MyWindow(string localStringParam)
    {
        string localStringVar = "a local variable";
        this._button = new Button();
        // place the button in the window
        this._button.Click += new RoutedEventHandler(
            delegate(object sender, RoutedEventArgs args)
            {
                this._numClicked += 1;
                MessageBox.Show("Param was: " + localStringParam + 
                     " and local var " + localStringVar +
                     " button clicked " + this._numClicked + " times");
            });
    }
}

Here we created an anonymous delegate - a function which is not given an explicit name. The only way to refer to this function is using the RoutedEventHandler delegate object. Furthermore, this function exists in the scope of the MyWindow constructor, so it can access all local parameters, variables, and the member instance "this". It will continue to hold references to the local variables and parameters even after the MyWindow constructor exits.

As a side note, the delegate will also hold a reference to the object instance - "this" - even after all other references to the class a removed. Therefore, to ensure that a class is garbage collected, all delegates to a non-static member method (or delegates created in the scope of one) should be removed.

antonm
All asnwers were useful and complementary. Thanks to all of you.I will read with care all answers and keep on trying. Thanks again :D
George
+1  A: 

You can think of delegates as a way to view code as data. If you create a delegate, it is a type. Variables of this type may point to specific methods (that comply with the delegate definition).

That means that you can treat a piece of code as data and for instance pass it to a method. Since delegates point to code (or null), you may also invoke the code that it points to via the variable.

That allows for some very useful patterns. The classic example is how to sort a collection. By allowing the caller to supply a delegate that implements what it means to sort specific elements, the sorting method doesn't have to know anything about this.

The same idea is used extensively with a lot of methods for LINQ. I.e. you pass in a delegate (or more commonly a lambda) which handles some specific task, and the LINQ method in question will call this in order to complete the task.

Brian Rasmussen