delegate

*■ Delegate* 
• a delegate is a type that represents references to methods with a specific parameter list and return type.
• It is similar to a function pointer in C or C++, but it is type-safe and object-oriented.
• It allows you to store the address of a method and call it later, even without knowing which method you're calling at compile time. 
• Method Reference : A delegate can hold a reference to a method, and you can invoke that method through the delegate. The method can be static or an instance method.
• Type-Safe : Delegates ensure that the method signature (parameters and return type) matches the delegate's signature, providing type safety.
• Delegates are type-safe, meaning they ensure that the method being called matches the expected signature, reducing runtime errors.
• Multicast : A delegate can reference more than one method at a time, meaning it can invoke multiple methods in a chain. This is useful for event handling.
➤ Rules for creating delegate 
• method must have the same return type and parameter types as the delegate.
• Method name and delegate name can be same but it's generally not recommended as it can lead to confusion. 
• We generally define delegate under namespace. 

1) Defining a Delegate:

[modifier] delegate [return type] [delegate-name] ([parameter-lists])

For ex :- 
public delegate int MathOperation(int x, int y);


2) creating a method matching the delegate signature

class Calculator {
public static int Add(int a, int b)
{
    return a + b;
}

3) Instantiating a delegate
• Create an instance of the delegate and assign it the method you want it to reference. 
There are two ways to do this 
1)
MathOperation mo = new MathOperation(Add);

If method is non static 
Calculator obj=new Calculator();
MathOperation mo = new MathOperation(obj. Add);


2) 
You can assign a method directly to a delegate without using the 'new' keyword

MathOperation mo = Add;

4) Invoke the Delegate
• Call the method through the delegate using the delegate instance.
int result = mo(5, 3);    // Calls the Add method
Console.WriteLine(result); // Output: 8




using System;

// 1. Delegate for methods with a return type
public delegate int CalcDelegate(int x, int y);
    
// 2. Delegate for void methods
public delegate void CalcVoidDelegate(int x, int y);




            *➤ Example* 
___________________________________


// declaring delegate for  method with return type
public delegate int CalcDelegate(int x, int y);

// declaring delegate for void method 
public delegate void CalcVoidDelegate(int x, int y);

// class
public class Calculator
{
    // 1. Static method with return type
    public static int Add(int a, int b)
    {
        return a + b;
    }

    // 2. Void static method
    public static void Subtract(int a, int b)
    {
        Console.WriteLine("Subtract: " + (a - b));
    }

    // 3. Non-static method with return type
    public int Multiply(int a, int b)
    {
        return a * b;
    }

    // 4. Void non-static method
    public void Divide(int a, int b)
    {
            Console.WriteLine("Divide: " + (a / b));
        
    }
    
      // Main method 


public static void Main()
  {
        /* Static methods  */

  CalcDelegate addObj = Add;   // Static method with return type

        CalcVoidDelegate subObj = Subtract;           // Void static method


        /*Non-static methods */

   Calculator obj = new Calculator();
   CalcDelegate mulObj = obj.Multiply;     // Non-static method with return type


        CalcVoidDelegate divObj = obj.Divide;               // Void non-static method




        /*  Invoke static methods     */

        Console.WriteLine("Add: " + addObj(10, 5)); // Output:  Add: 15
       
  subObj(10, 5);      // Output: Subtract: 5

        /* Invoke non-static methods */

        Console.WriteLine("Multiply: " + mulObj(10, 5));   // Output: Multiply: 50

        divObj(10, 5);            // Output: Divide: 2
    }
    
    
}
___________________________________

Delegates Can Be Multicast:

➤ Multicast Delegate
• A multicast delegate in C# is a delegate that can hold references to more than one method.
• When you invoke a multicast delegate, all methods it references are invoked in the order they were added.
• All of the functions that the multicast delegate references will be called when the delegate is called. 
• All method signatures should match if you want to use a delegate to call multiple methods.
   
   ➤ Key points about multicast delegate

➔ return type handling 
• If the delegate has a return type (non-void), only the result of the last method in the invocation list is returned. Previous return values are discarded. (below, after few lines are the example see & understand ) 
• If the delegate returns void, all methods in the invocation list are executed, and each method can affect the program independently.
➔ combining methods
• Methods are added to delegates using the + or += operator.
➔ Removing methods
• You can remove a method from a multicast delegate using the -= operator.
➔ Use 
• Multicast delegates are commonly used for event handling, logging, or notifications where multiple methods need to be invoked in response to a single event.

  ➤  Multicast delegate example
___________________________________
using System;

// Declare a delegate with a return type of int
public delegate int CalcDelegate(int a, int b);

//  calculator class 
public class Calculator
{
    public int Add(int a, int b)
    {
        int result = a + b;
        Console.WriteLine("Add: " + result);
        return result;
    }

    public int Subtract(int a, int b)
    {
        int result = a - b;
        Console.WriteLine("Subtract: " + result);
        return result;
    }

    public int Multiply(int a, int b)
    {
        int result = a * b;
        Console.WriteLine("Multiply: " + result);
        return result;
    }

    public int Divide(int a, int b)
    {
        int result = a / b;
        Console.WriteLine("Divide: " + result);
        return result;
    }
    
    // Main Method 
    public static void Main()
    {
      // creating instance of Calculator class 
        Calculator obj = new Calculator();

        /* Create a multicast delegate */
        CalcDelegate calc = obj.Add;
        calc += obj.Subtract;
        calc += obj.Multiply;
        calc += obj.Divide;

          /* Invoke the multicast delegate */
// & 
    /* Since the delegate has a return type, only the result of the last method is returned.  
Only the value of Divide method(which is in last) is returned */

       int final_res = calc(20, 5);

      Console.WriteLine("Final Result: " + final_res); // Output: 4
    }
}

Output :-
Add: 25
Subtract: 15
Multiply: 100
Divide: 4
Final Result: 4
___________________________________





 *■ Event* 

Read about event from pdf in classroom (pdf name - delegate and thread)

Comments

Popular posts from this blog

Raster scan Vs Vector Scan

Inheritance

unit -1 Introduction of Image processing