Anonymous Methods in C# using example
- By Gurunatha Dogi in C#
- Nov 22nd, 2016
- 19531
- 0
Introduction
Anonymous methods are moreover related to Delegates. Anonymous methods are extension and improvement to delegates. They make the code easy and more readable. Anonymous methods increase performance of the application overall as and when used instead traditional delegate. With anonymous methods you can use delegate within same function.
In this article we will see how to write code of anonymous methods in C# and compare it with traditional delegate. Also we will practically see how performance increases with use anonymous methods over traditional delegates.
This article written by "Ahtesham Shaikh", Ahtesham Shaikh is C# and .NETtrainer, He not only writes for C# but also take trainings on C# for freshers and mid-level developers.
Normally written Delegate Code
Below is simple sample code of delegate which is written in a normal way where "Add" method is written separately then delegate "PointerAddFun"is created. Thereafter pointer "pointadd" is then pointed to "Add" method. Finally the pointer is invoked and given values perform add operation then results are displayed on the console prompt.
Anonymous Methods
As said earlier with the use of Anonymous Methods we can reduce the line of code by removing overhead method which does the add operation as done in this example and write inline block of code within the Main method to perform add operation. Using Anonymous Methods is more appropriate where we have simple and single line of method likewise we have in this example.
Now we have seen how to write both traditional written delegate and also seen how to code using Anonymous Methods.
It is the time to do comparison between both of the methods and check out which performs better.
Monitoring Anonymous methods
In order to do comparison we will write two "For loop" codes, first loop code which will run for 10 times and under to first loop code there will be second loop code which will run 1000 times. Under second loop code which is running 1000 times will execute anonymous delegate code within it.
Below image shown are the full steps: -
- Create first loop which is going to run 10 times and here is the code for it
- Within this first loop create second loop which will run 1000 times in such a way that anonymous delegate lies within the scope of this loop as shown in the image below.
- Import diagnostic namespace which will run stopwatch and show time taken run anonymous delegate method. To import namespace use below code
- Create object of stop watch under diagnostic class with the following code
- Now under first loop write code to reset and then start stopwatch as written below
- At the end where delegate code ends just declare variable name "z" then invoke pointer and pass the value to addition (3, 3).
- Once the loop is executed then stop the stop watch by using below statement
- Write a display line on console prompt time taken for each loop which runs 10 times and internally each loop run 1000 times. This will be done using ElapsedTicks of diagnostic class.
for (int y = 0; y < 10; y++)
for (int x = 0; x < 1000; x++)
usingSystem.Diagnostics;
Stopwatch objstpwtch = new Stopwatch();
objstpwtch.Reset(); objstpwtch.Start();
int z = pointadd.Invoke(3 ,3);
objstpwtch.Stop();
Console.WriteLine(objstpwtch.ElapsedTicks);
Once writing of code is completed then build the entire solution and click on ctrl + F5 on keyboard to execute and see the result.
On console prompt you will see the execution result time taken for each 10 loops and each loop executed 1000 times.
Monitoring Delegate with normal way
Since the results for anonymous methods are out now we will recode it. All steps are same as we have seen aboveonly need is to remove existing in line code delegate and create a separate Add method outside. Once the Add method is created tie it up with pointer delegate. Below is the code which should be written for pointing delegate to method
PointerAddFunpointAdd = Add;
Rebuilt the solution and run the code using ctrl + F5 key on keyboard
Result will be seen on the command prompt for normal delegate
We have taken results of both the methods and put it on the table in front of you for ease of comparison. From below table, result for anonymous method where we have inline delegate code shows less time to process the loop as compare to normal way of delegate where Add method is outside.
Anonymous method Delegate |
Normal way Delegate |
454 | 4709 |
96 | 193 |
88 | 176 |
71 | 186 |
57 | 175 |
55 | 184 |
55 | 164 |
54 | 183 |
54 | 176 |
52 | 187 |
So it is better to use anonymous methods inline delegate code under the circumstances where we have small and simple methods instead of creating full overhead methods outside.
Secondly performance increases with use of anonymous methods as we have tested above and got the results.
This article is a small water droplet from the .NET knowledge of pond. There are many other important topics which are essential to become successful programmer here is the site which we would like to share questpond.com which is answer for almost all questions in C# and .NET programming.
Also below is a video from their latest C# 100 hrs series hope you will like it as a fresher: -
Gurunatha Dogi
Gurunatha Dogi is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more..... read more