|Deep C# - Anonymous Methods, Lambdas And Closures|
|Written by Mike James|
|Monday, 19 September 2016|
Page 1 of 5
Anonymous methods aren't particularly new, but they have hidden depths and lead on to lambdas and the idea of a closure. These are all important ideas in modern programming.
This is a chapter of our ebook on C#, a work in progress.
Buy Now From Amazon
Anonymous methods were introduced back in .NET 2.0 and while they sound like something designed to implement “dirty” shortcuts they are a welcome addition to C#. In modern C# they have been superseded by the lambda expressions but there is still one thing that an anonymous method can do that a lambda can't so they are still worth knowing about. In addition statement lambdas are just a slightly different syntax for anonymous methods so they are the foundations upon which lambdas are built.
The big problem with anonymous methods is figuring out what the problem is that they are designed to solve.
So let’s take a look at what they are for.
On one level anonymous methods are just about making delegates easier to create. Let's go through the stages of creating a delegate.
A delegate is just an object that “wraps” a function.
It is what you need when functions are not in themselves first class objects. That is you can't pass a function as argument to another function so you have to wrap it in an object so that you can pass the object and a delegate is just an object designed for wrapping a function.
Before you can use a delegate to wrap a function you have to create a delegate type that has the signature of the function you want to wrap. That is every delegate wrapper carries information about the function it wraps in its type - this is used to detect simple errors.
Then you instantiate the type, wrap the function and use it.
So the steps to create and use a delegate are:
What all this means is that you have to invent multiple names for what in most cases is a single idea -
For example, if you want to wrap a “Hello World” function you first create a suitable delegate type:
then you have to create the function within some class or other:
and finally create an instance of the delegate type specifying the function that it is to wrap:
Calling the function via the delegate is just a matter of using its name:
You can see that we have had to invent three names:
This is fine if you are going to create multiple instances of the type and wrap multiple functions but in most cases the type, the delegate and the method are more or less a single entity.
That is you create a delegate because you want to use a method as if it was an object and often this is a one-off requirement.
|Last Updated ( Thursday, 22 September 2016 )|