delegates.md - brainchildservices/curriculum GitHub Wiki

SLIDE-1

Delegates

A delegate is a type safe function pointer.

The delegate is a reference type data type that defines the method signature.

A delegate holds the reference to a method and then calls the method for execution.

SLIDE-2

Why do we need delegates in C#?

We have seen that we can pass objects to method parameters. In the same way, programmers often needs to pass a method as a parameter of other methods. For this purpose we create and use delegates.

There are three steps involved while working with delegates:

  1. Declare a delegate
  2. Set a target method
  3. Invoke a delegate

One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature.

SLIDE-3

1. Declare a delegate

image

The process of declaring a delegate is simple, we just need to add the delegate keyword to the method signature that includes the return type as well.

Copy the method signature line, add the keyword delegate before the return type and put semicolon at the end of the statement.

Exclude the static keyword in delegate declaration even if the method is static.

Like given -- https://dotnetfiddle.net/iBWial

                        using System;

                        public delegate string Print(string message);
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Console.WriteLine("Hello World");
                        	}

                        	public string Print(string message)
                        	{
                        		return "Hello " + message;
                        	}
                        }

SLIDE-4

Example1:

https://dotnetfiddle.net/Fxaa41

                        using System;

                        public delegate string PrintDelegate(string message); 		//Step1: Declaring a delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Console.WriteLine("Hello World");
                        	}

                        	public string Print(string message)
                        	{
                        		return "Hello " + message;
                        	}
                        }

SLIDE-5

Example2:

https://dotnetfiddle.net/vRmFeE

                        using System;

                        public delegate void AddDelegate(int a, int b);			//Step1: Declare the Delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Console.WriteLine("Hello World");
                        	}

                        	public void Add(int a, int b)
                        	{
                        		Console.WriteLine(a + b);
                        	}
                        }

SLIDE-6

Example3:

https://dotnetfiddle.net/1Cvj3X

                        using System;

                        public delegate void DiffDelegate(int x, int y); 			//Step1: Declare the Delegate
                        															//The static keyword is not used while declaring the delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                            
                        	}

                        	public static void Diff(int x, int y)
                        	{
                        		Console.WriteLine(x - y);
                        	}
                        }

A delegate is a class that encapsulates a method signature.

SLIDE-7

2. Set a target method

In this stage, we create an instance of the delegate declared in step 1 and we pass the name of the target method as parameter to the constructor. This is similar to creating an instance of a class. But here we have to pass a method as the constructor parameter. The method passed must have the same signature as the signature of the delegate.
The instance of a class is called an object, while instance of a delegate is called a delegate itself.

Example1:

https://dotnetfiddle.net/J76PTe

                        using System;

                        public delegate string PrintDelegate(string message); 			//Step1: Declaring a delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Program P = new Program();
                        		PrintDelegate PrintDel = new PrintDelegate(P.Print); 	//Step 2: Creating instance of delegate and passing the target method
                        	}

                        	public string Print(string message)
                        	{
                        		return "Hello " + message;
                        	}
                        }

SLIDE-8

Example2:

https://dotnetfiddle.net/qaMg2k

                        using System;

                        public delegate void AddDelegate(int a, int b); 		//Step1: Declare the Delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Program P = new Program();
                        		AddDelegate AddDel = new AddDelegate(P.Add); 	//Step2: Create instance of Delegate and passing the target method
                        	}

                        	public void Add(int a, int b)
                        	{
                        		Console.WriteLine(a + b);
                        	}
                        }

SLIDE-9

Example3:

https://dotnetfiddle.net/iTlajB

                        using System;

                        public delegate void DiffDelegate(int x, int y); 			//Step1: Declare the Delegate
                        															//The static keyword is not used while declaring the delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		DiffDelegate DiffDel=new DiffDelegate(Diff);		//Step2: Create instance of Delegate and passing the target method
                        															//Here we are passing the target method without object because the Diff method is static and
                        															//exists in the same class.
                        	}

                        	public static void Diff(int x, int y)
                        	{
                        		Console.WriteLine(x - y);
                        	}
                        }

SLIDE-10

3. Invoke a delegate In the third step, we call the target method. The target method can be invoked in 2 ways:

  1. Using the () operator or
  2. Using the Invoke() method

Example1:

https://dotnetfiddle.net/DIitNI

                        using System;

                        public delegate string PrintDelegate(string message); 				//Step1: Declaring a delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Program P = new Program();
                        		PrintDelegate PrintDel = new PrintDelegate(P.Print); 		//Step 2: Creating instance of delegate and passing the target method

                        		string result1 = PrintDel("John"); 							//Step 3: Invoking the Delegate using () operator.
                        		Console.WriteLine(result1);

                        		string result2 = PrintDel.Invoke("Peter"); 					//Step 3: Invoking the Delegate using Invoke method.
                        		Console.WriteLine(result2);
                        	}

                        	public string Print(string message)
                        	{
                        		return "Hello " + message;
                        	}
                        }

SLIDE-11

Example2:

https://dotnetfiddle.net/vyS0VR

                        using System;

                        public delegate void AddDelegate(int a, int b); 		//Step1: Declare the Delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Program P = new Program();
                        		AddDelegate AddDel = new AddDelegate(P.Add); 	//Step2: Create instance of Delegate and passing the target method

                        		AddDel(10, 25);									//Step 3: Invoking the Delegate using () operator.

                        		AddDel(100, 234);								//Step 3: Invoking the Delegate using Invoke method.
                        	}

                        	public void Add(int a, int b)
                        	{
                        		Console.WriteLine(a + b);
                        	}
                        }

SLIDE-12

Example3:

https://dotnetfiddle.net/PaUx2M

                        using System;

                        public delegate void DiffDelegate(int x, int y); 					//Step1: Declare the Delegate
                        																	//The static keyword is not used while declaring the delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		DiffDelegate DiffDel = new DiffDelegate(Diff); 				//Step2: Create instance of Delegate and passing the target method
                        																	//Here we are passing the target method without object because the Diff method is static and
                        																	//exists in the same class.

                        		DiffDel(33, 14);											//Step 3: Invoking the Delegate using () operator.

                        		DiffDel.Invoke(45, 34);										//Step 3: Invoking the Delegate using Invoke method.
                        	}

                        	public static void Diff(int x, int y)
                        	{
                        		Console.WriteLine(x - y);
                        	}
                        }

Most often Delegates are declared outside the classes just under the namespace/

SLIDE-13

// Delegates declared outside the class, ie under the namespace

https://dotnetfiddle.net/1dMgvs

                        using System;
                        // Delegates declared outside the class
                        public delegate void AddNumDelegate(int a, int b);
                        public delegate void SubNumDelegate(int a, int b);

                        public class Calculator
                        {
                        	public void sum(int a, int b)
                            {
                                Console.WriteLine("{0}+{1}={2}",a,b,a+b);
                            }
                        	public void diff(int a, int b)
                            {
                                Console.WriteLine("{0}-{1}={2}",a,b,a-b);
                            }
                        }

                        public class Program
                        {
                        	public static void Main()
                        	{
                        		Calculator Calc=new Calculator();

                        		AddNumDelegate myAddDelegate=new AddNumDelegate(Calc.sum);
                        		myAddDelegate(144,48);

                        		SubNumDelegate mySubDelegate=new SubNumDelegate(Calc.diff);
                        		mySubDelegate(123,45);
                        	}
                        }

SLIDE-14

//When delegate is declared in the class where it is called

In this case

https://dotnetfiddle.net/PwOl5s

                        using System;

                        //When delegate is declared in the class where it is called
                        public class Calculator
                        {
                        	public void Sum(int a, int b)
                        	{
                        		Console.WriteLine("{0}+{1}={2}", a, b, a + b);
                        	}

                        	public void Diff(int a, int b)
                        	{
                        		Console.WriteLine("{0}-{1}={2}", a, b, a - b);
                        	}
                        }

                        public class Program
                        {
                        	public delegate void AddNumDelegate(int a, int b);
                        	public delegate void SubNumDelegate(int a, int b);
                        	public static void Main()
                        	{
                        		Calculator Calc = new Calculator();

                        		AddNumDelegate myAddDelegate = Calc.Sum;
                        		myAddDelegate(144, 48);

                        		SubNumDelegate mySubDelegate = Calc.Diff;
                        		mySubDelegate(123, 45);
                        	}
                        }

SLIDE-15

Passing a Delegate to a method

https://dotnetfiddle.net/KZDcFZ

                        using System;

                        public delegate string PrintDelegate(string name); 				//2. Create the Delegate
                        public class Program
                        {
                        	public static void Main()
                        	{
                        		PrintDelegate printDel = new PrintDelegate(Print); 		//5. Create instance of Delegate 
                        		Printer(printDel); //6. Call the method
                        	}

                        	public static string Print(string name) 					//1. Create the method that should be passed to delegate
                        	{
                        		return "Hello " + name + ". Good Morning";
                        	}

                        	public static void Printer(PrintDelegate printDel) 			//3.Create the method that takes delegate as parameter and pass the delegate as     parameter
                        	{
                        		for (int i = 0; i < 10; i++)
                        		{
                        			Console.WriteLine(printDel("John")); 				//4. Invoke the delegate
                        		}
                        	}
                        }

SLIDE-16

Uses of Delegates:

  1. Type safety during method calls
  2. Helps with encapsulation of methods

SOME FACTS ABOUT DELEGATES

  1. Delegates are reference type but instead of referencing objects it reference methods.
  2. Delegates have no method body.
  3. Delegates are type-safe, object-oriented and secure.
  4. A Delegate is a function pointer that allows you to reference a method.
  5. Delegates encapsulate methods.
  6. A Function that is added to delegates must have same return type and same signature as delegate.

References:
https://www.c-sharpcorner.com/UploadFile/puranindia/C-Sharp-net-delegates-and-events/
https://www.geeksforgeeks.org/c-sharp-delegates/
https://www.tutorialsteacher.com/csharp/csharp-delegates
https://www.youtube.com/watch?v=D8PyJyI4kb4
https://www.youtube.com/watch?v=ifbYA8hyvjc
https://www.codesdope.com/course/c-sharp-delegate/