what is a delegate?

BitLost

Active member
Joined
Dec 10, 2016
Messages
35
Programming Experience
Beginner
I have been working away to try and learn ASP.Net. Been doing lots of tutorials on Asp.Net and reading online information...but...the more I read the more confused I become.

It seems to me I need to understand some of the underlying why to be able to grasp what I am doing. For example apparently there are delegates. Okay. So what is a delegate and why do I use it and where would I use it and what would the alternative be. Or there is a lambada expression. Apparently it is a non declared version of a function or something like that. Therefore you can have a statement like (i=>i.Courses.Course) nice for some. How does this know where to get the information from? Why does it know? I am full of a million of these type of questions.

Logically there has to be a clearer explanation than the MSDN sites, sometimes I find the other sites explanations even more confusing than helpful. Somewhere there has to be a simple baby step guide to this system...I hope.
 
Like most things in programming, delegates are so named because they mimic the behaviour of something so named in the "real world". What is a delegate usually? It's a person who is authorised to act on behalf of another person or entity. That is effectively what a delegate does in programming. Consider, for instance, that your country has a delegate to the UN. That person goes to UN conferences and casts their vote. In effect, your country has cast their vote without ever being at the meeting because the delegate did it for them.

In C#, a delegate is an object that holds a reference to a method. Invoking the delegate will invoke that method. This means that you can create a delegate that refers to method A of object B and then pass that delegate object around like you would any other object. You could pass it to object C that could pass it to object D that could then invoke it. That would cause method A of object B to be executed by object D without object D having any idea what object B is or even that it exists.

Delegates are useful because it allows you to write code that can execute arbitrary methods without caring where they come from or what they actually do. All you have to care about is that their signature matches a particular pattern. For instance, the Array.Sort method has an overload that accepts as an argument a Comparison<T> delegate. That delegate is declared with a return type of 'int' and two parameters of type 'T'. That Array.Sort method will invoke that method repeatedly to compare pairs of elements and use the values it returns to determine the final order of the elements. The Array class doesn't care where the actual method is declared or what it does. It simply invokes the delegate that refers to that method.

What that means for the user of the Array.Sort method is that they can write as many methods as they like that match that signature and pass them to the Array.Sort method and have their arrays sorted in any way they like. For instance, you might have a Person class that has GivenName, FamilyName and DateOfBirth properties and you might have an array of instances of that class. You can call Array.Sort and pass that array and then pass a Comparison<Person> delegate that compares Person objects by FamilyName and then GivenName or by GivenName and then FamilyName or by DateOfBirth in order to sort in different ways. That delegate can also refer to named methods if that's appropriate or, if you need something more dynamic or just want something more succinct, it can refer to a lambda expression, which is a type of anonymous method.
private void SortPeopleByFamilyNameThenGivenName(Person[] people)
{
    // Use a delegate to a named method.
    Array.Sort(people, ComparePeopleByFamilyNameThenGivenName);
}

private void SortPeopleByDateOfBirth(Person[] people)
{
    // Use a lambda expression.
    Array.Sort(people, (x, y) => x.DateOfBirth.CompareTo(y.DateOfBirth));
}

private int ComparePeopleByFamilyNameThenGivenName(Person x, Person y)
{
    var result = x.FamilyName.CompareTo(y.FamilyName);

    if (result == 0)
    {
        result = x.GivenName.CompareTo(y.GivenName);
    }

    return result;
}
One of the most common uses for delegates has been event handlers. If you have handled the Click event of a Button then you've used delegates, although you probably didn't realise it. In that case, you write a method in your form that matches a particular signature and then the act of registering it as an event handler means creating a delegate to it that is then passed to the Button. When the Button is clicked, it goes to the collection of delegates it has for its Click event and invokes them, thus executing the method declared in your form.

These days, the most common use for delegates is when using LINQ. Lambda expressions were introduced in order to streamline LINQ because almost every LINQ query involves one or more delegates. Creating a LINQ query involves collecting a bunch of delegates into a particular structure and executing the query mean invoking those delegates in the appropriate order.
 

Latest posts

Back
Top Bottom