1. Back To Blog

C# interview questions: - Explain anonymous methods in .NET?

C# interview questions: - Explain  anonymous methods in .NET?

Anonymous Methods: - In simple words Anonymous Methods means method which are coded inline or methods without method name.

An anonymous method uses the keyword delegate, instead of method name.

Anonymous Methods help you to avoid overhead of creating a method for simple lines of code where you want your delegates to be pointed out.

Below is the simple code snippet without Anonymous Method.




Now, let's how the above code snippet will look like with Anonymous Method.



In the above code snippet you can see that I have eliminated the Add function
and just have created anonymous method with a small block of function.

Anonymous methods also help to increase performance of the code.

Let's demonstrate a simple example to see how exactly Anonymous Method help to increase performance.

In this example we will first create method with Named Method and see the performance and later we will create Anonymous Method and see the performance done by anonymous method and will later compare both the methods performance to see which of the method's performance is better.

Step1: - Create a new project > File > New > Project > Console Application.




Now import using System.Diagnostics; in order to measure performance.

Now, let's create a simple Add method which will return addition of two numbers.




In the above code snippet I have created two for loop. The outer for loop which is having "i" variable will run the block 10 times and inner for loop which is having "j" variable will run the block till it exceeds to value 1000 and also I have created object of StopWatch to measure the performance.

Now just run your application and will see result like below output diagram.




Step2: - Now, let's see how we can create a simple Anonymous Method like below code snippet.




Similarly, in the above code snippet I have created two for loop. The outer for loop which is having "i" variable will run the block 10 times and inner for loop which is having "j" variable will run the block till it exceeds to value 1000 and also I have created object of StopWatch to measure the performance.

Now just run the application and will see the result like below output diagram.




Now let's compare both the result and see whose performance is better.

  


In above results you can clearly see that performance of Anonymous Method is much better than the method with Method named.

You can also view the following video on anonymous methods in C#: -



Visit the following for more learning tutorials on Most asked c# interview questions

Regards,


Also visit for more author's blog on interview questions and answers for c#

Shiv Prasad Koirala

Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social