Learn about the delegates in this lesson.

Delegates: Definition

A delegate is a combination of a function pointer and the context that it should be executed in. Delegates also support closures in D. Closures are a feature supported by many functional programming languages.

As we discussed in the lifetimes and fundamental operations chapter, the lifetime of a variable ends upon leaving the scope that it is defined in:

    int increment = 10; 
    // ...
} // ← the life of 'increment' ends here

That is why the address of such a local variable cannot be returned from a function.

Let’s imagine that increment is a local variable of a function that itself returns a function. Let’s make it so that the returned lambda happens to use that local variable:

Get hands-on with 1000+ tech skills courses.