AnonymousMethods.md - brainchildservices/curriculum GitHub Wiki

SLIDE-1

Anonymous Methods In C#

Anonymous methods are unnamed methods in a code that can be defined using the delegate keyword.
They only require a body and not a name or a return type.
Anonymous methods allow users to write inline codes rather than explicit methods. Anonymous methods are used when the method body is very small and should not be used with unsafe codes.
Anonymous methods helps us with not having to look around for the implementation of the code.

SLIDE-2

Example 1:

  • A normal process to create a delegate for a method and invoking it:

Step1: Create a method
Step2: Create a delegate
Step3: Create Delegate instance
Step4: Invoke the delegate

https://dotnetfiddle.net/OqhxwX

                        using System;

                        public delegate string PrintDelegate(string name);				//2. Create the Delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		PrintDelegate printDel = new PrintDelegate(Print);		//3. Create instance of Delegate
                        		string result = printDel("John");						//4. Invoke the Delegate
                        		Console.WriteLine(result);								//5. Print the result
                        	}

                        	public static string Print(string name)						//1. Create the method
                        	{
                        		return "Hello " + name + ". Good Morning";
                        	}
                        }

SLIDE-2(DOWNWARDS)

  • Now if we are using Anonymous method:

Step1: Create a delegate
Step2: Create Delegate instance. Here is where we would see the difference. The instance is created using the delegate keyword. The parameter is specified in parenthesis with the method body inside curly braces. There is **semicolon ;**after the curly braces of the method body.
Step3: Invoke the delegate

https://dotnetfiddle.net/AMKdi1

                        using System;

                        public delegate string PrintDelegate(string name);				//1. Create the Delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		PrintDelegate printDel = delegate(string name)
                        		{
                        			return "Hello " + name + ". Good Morning";
                        		};														//2. Create instance of Delegate using delegate keyword and adding the method bodu
                        		string result = printDel("John");						//3. Invoke the Delegate
                        		Console.WriteLine(result);								//4. Print the result
                        	}

                        	/*public static string Print(string name)					//1. Create the method - No longer needed
                        	{
                        		return "Hello " + name + ". Good Morning";
                        	}*/
                        }

SLIDE-3

Example2:

Without using anonymous method

https://dotnetfiddle.net/bzNROk

                        using System;

                        public delegate void SumDelegate(int a, int b); 		//Step2: Created Delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		SumDelegate sumDel = new SumDelegate(Sum); 		//Step3: Created instance of delegate
                        		sumDel(2, 3); 									//Step4: Invoke the delegate
                        	}

                        	public static void Sum(int a, int b) 				//Step1: Create method
                        	{
                        		Console.WriteLine("{0}+{1}={2}", a, b, a + b);
                        	}
                        }

SLIDE-3(DOWNWARDS)

Using anonymous method

https://dotnetfiddle.net/c0gxB9

                        using System;

                        public delegate void SumDelegate(int a, int b); 				//Step1: Created Delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		SumDelegate sumDel = delegate (int a, int b) 			//Step2: Created instance of delegate and pass method
                        		{
                        			Console.WriteLine("{0}+{1}={2}", a, b, a + b);
                        		};
                        		sumDel(2, 3); 											//Step3: Invoke the delegate
                        	}
                        }

SLIDE-4

StopWatch:

Stop watch comes under System.Diagnostics namespace
We can use it to count the time for the completion of an operation.
Create an instance of Stopwatch, reset the stop watch, start the stop watch and then stop it. We can use the methods of stop watch to find the elapsed times.

https://dotnetfiddle.net/Hx6Q0P

                        using System;
                        using System.Diagnostics;

                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Stopwatch time = new Stopwatch();
                        		time.Reset();
                        		time.Start();

                        		int sum = 0;
                        		for (int i = 0; i < 1000000000; i++)
                        		{
                        			sum += i;
                        		}

                        		time.Stop();

                        		Console.WriteLine(time.Elapsed.ToString());
                        		Console.WriteLine(time.ElapsedMilliseconds.ToString());
                        		Console.WriteLine(time.ElapsedTicks.ToString());
                        	}
                        }

SLIDE-5

Analysing the performance of Anonymous methods:

Case1: Without using Anonymous Method:

We have a Add method which adds two numbers and we have a delegate for it that gets called in the Main method once.

https://dotnetfiddle.net/NKzanL

                        using System;

                        public delegate void addDelegate(int a, int b);
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		addDelegate addDel = new addDelegate(Add);
                        		addDel.Invoke(4, 5);
                        	}

                        	public static void Add(int a, int b)
                        	{
                        		int c = a + b;
                        	}
                        }

SLIDE-5(DOWNWARDS)

Now we are going to loop through creating delegate instance and invoking 5000000 times.

https://dotnetfiddle.net/icbLAv

                        using System;

                        public delegate void addDelegate(int a, int b);
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		for (int i = 0; i < 500; i++)
                        		{
                        			addDelegate addDel = new addDelegate(Add);
                        			addDel.Invoke(4, 5);
                        		}
                        	}

                        	public static void Add(int a, int b)
                        	{
                        		int c = a + b;
                        	}
                        }

SLIDE-5(DOWNWARDS)

We are going to use the stopwatch to find the time elapsed

https://dotnetfiddle.net/Uaz2Vj

                        using System;
                        using System.Diagnostics;

                        public delegate void addDelegate(int a, int b);
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Stopwatch time = new Stopwatch();
                        		time.Reset();
                        		time.Start();

                        		for (int i = 0; i < 5000000; i++)
                        		{
                        			addDelegate addDel = new addDelegate(Add);
                        			addDel.Invoke(4, 5);
                        		}

                        		time.Stop();
                        		Console.WriteLine(time.ElapsedTicks.ToString());
                        	}

                        	public static void Add(int a, int b)
                        	{
                        		int c = a + b;
                        	}
                        }

SLIDE-6

Case2: Using Anonymous Method:

Creating anonuymouse method that adds two numbers and saves it to another variable

https://dotnetfiddle.net/IF9bh4

                        using System;

                        public delegate void addDelegate(int a, int b);
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		addDelegate addDel = delegate(int a, int b)
                        		{
                        			int c = a + b;
                        		};
                        		addDel.Invoke(4, 5);
                        	}
                        }

SLIDE-6(DOWNWARDS)

Now we are going to loop through creating anonymous method and invoking 5000000 times.

https://dotnetfiddle.net/iNngwN

                        using System;

                        public delegate void addDelegate(int a, int b);
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		for (int i = 0; i < 5000000; i++)
                        		{
                        			addDelegate addDel = delegate (int a, int b)
                        			{
                        				int c = a + b;
                        			};
                        			addDel.Invoke(4, 5);
                        		}
                        	}
                        }

SLIDE-6(DOWNWARDS)

We are going to use the stopwatch to find the time elapsed

https://dotnetfiddle.net/c9uaXc

                        using System;
                        using System.Diagnostics;

                        public delegate void addDelegate(int a, int b);
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Stopwatch time = new Stopwatch();
                        		time.Reset();
                        		time.Start();
                        		for (int i = 0; i < 5000000; i++)
                        		{
                        			addDelegate addDel = delegate (int a, int b)
                        			{
                        				int c = a + b;
                        			};
                        			addDel.Invoke(4, 5);
                        		}

                        		time.Stop();
                        		Console.WriteLine(time.ElapsedTicks.ToString());
                        	}
                        }

Comparing Case1 and Case2, we could see that time taken with anonymous method is very less than the case where we didn'tuse anonymous method.

References:
https://www.c-sharpcorner.com/article/anonymous-methods-in-c-sharp/
https://www.knowledgehut.com/tutorials/csharp/csharp-anonymous-methods
https://www.youtube.com/watch?v=OxFdbsbY3to