Delegates, Why? [duplicate]

Changing functionality at runtime is not what delegates accomplish.

Basically, delegates save you a crapload of typing.

For instance:

class Person
    public string Name { get; }
    public int Age { get; }
    public double Height { get; }
    public double Weight { get; }

IEnumerable<Person> people = GetPeople();

var orderedByName = people.OrderBy(p => p.Name);
var orderedByAge = people.OrderBy(p => p.Age);
var orderedByHeight = people.OrderBy(p => p.Height);
var orderedByWeight = people.OrderBy(p => p.Weight);

In the above code, the p => p.Name, p => p.Age, etc. are all lambda expressions that evaluate to Func<Person, T> delegates (where T is string, int, double, and double, respectively).

Now let’s consider how we could’ve achieved the above without delegates. Instead of having the OrderBy method take a delegate parameter, we would have to forsake genericity and define these methods:

public static IEnumerable<Person> OrderByName(this IEnumerable<Person> people);
public static IEnumerable<Person> OrderByAge(this IEnumerable<Person> people);
public static IEnumerable<Person> OrderByHeight(this IEnumerable<Person> people);
public static IEnumerable<Person> OrderByWeight(this IEnumerable<Person> people);

This would totally suck. I mean, firstly, the code has become infinitely less reusable as it only applies to collections of the Person type. Additionally, we need to copy and paste the very same code four times, changing only 1 or 2 lines in each copy (where the relevant property of Person is referenced — otherwise it would all look the same)! This would quickly become an unmaintainable mess.

So delegates allow you to make your code more reusable and more maintainable by abstracting away certain behaviors within code that can be switched in and out.

Leave a Comment