In this post, we’ll explore ways to make method declaration more flexible.
Overview
- Delegates
- Lambda Expressions
- Closures
A closer look at
delegates
Delegates in .NET are used
as a mechanism to contain methods in flexible variables or even specify them
inline. This allows for additional implementation capabilities. Some more reading on delegates…
Some
sections to consider before continuing:
(A) Delegate variable, (B) Named method, (C) Delegate assignment and (D)
Initialization- Initialization using a named method
- Inline anonymous method declaration
- Generic anonymous inline delegate implementation
- Delegates as events
- Assign named event method using EventHandler (Win Forms):
- Adding an anonymous inline delegate method (Win Forms)
Lambda Expressions
- Basic inline lambda expressions
- Explicit inline Lambda expression
- Here is the same method but implicitly defined
- Iterating through generic List using Lambda expression
- Generic list manipulation
Closures
As
delegate placeholders can be assigned from logic (opposed to being defined
strictly in structure) it also provides opportunities to define relationships
between object methods and other objects.
Key
to this approach is the context in which the assigned delegate is executed. It
is not from the object that defined the placeholder delegate (Children) but
rather, in case of a named method delegate reference, the object that contains
the named method declaration (Parent).
Why
is this significant?
- Executes a level higher than itself, this opens great potencial for siblings actions to affect each other and global attributes of their parent.
- Because the delegates are assigned not defined in a set structure you can assign different methods to the same delegate placeholder.
E.g. here we have a math university class
that requires a global average property to be kept up to date every time a
student average changes.
- Create the parent object (MathClass)
- Create the child object (Student)
- Create a method to populate our class with test data
You can
download the source code for this post from GitHub.
Note:
It does not include the WinForm example and the startup class needs to change
to switch between examples.
Liked: the fact that you highlighted the differences. and the tip on using Invoke.
ReplyDeleteWished: you had added examples/situations of when you would use them.
Closure section - not that clear to me. I'll keep reading up on that - feels like it creates some sort of dependancy.