Skip to main content

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

1. Raster Scan Display   How It Works : A raster scan display works by painting an image on the screen pixel by pixel, row by row. It follows a systematic pattern where the electron beam (in CRT monitors) or the display elements (in modern LCD/LED screens) sweep across the screen from left to right, top to bottom, in a series of horizontal lines (scan lines). This process is akin to how a traditional TV screen works.   Process : The display draws the image starting from the top-left corner, moving to the right, then moves to the next row below, and repeats this process until the entire screen is filled. This pattern creates a grid of pixels, where each pixel can have a color and brightness level.   Characteristics : Pixel-based : The screen consists of a grid of pixels, and each pixel can have a distinct color and intensity. Continuous Image : Raster scan displays are capable of displaying detailed and complex images, including photographs and videos, because they break t...

Inheritance

*■ Inheritance*  • Inheritance is a concept in OOP that allows a class to inherit properties and behaviors (methods) from another class. • A class that inherits from another class is called a derived class (or subclass) • The class which gets inherited by another class is called the base class (or superclass). • Inheritance is possible only if there is is-a relationship between parent and child class. • constructors are not inherited in derived class, however the derived class can call default constructor implicitly and if there's a parameterised constructors in bass class then derived class can call it using 'base' keyword.  ____________________________________________  *➤ Rules of Inheritance*  1) C# supports single inheritance, meaning a class can inherit from only one base class. 2) A parent class constructor must be accessible in child class otherwise  inheritance will be not possible. 3) every class, whether user-defined or predefined implicitly derives fr...

unit -1 Introduction of Image processing

  What is Image Processing? Image processing is a method to perform operations on an image to enhance it or extract useful information. It is a type of signal processing where the input is an image, and the output may be either an image or characteristics/features associated with that image. Goals of Image Processing Image Enhancement : Improving visual appearance (e.g., contrast, sharpness) Image Restoration : Removing noise or distortion Image Compression : Reducing the amount of data required to represent an image Feature Extraction : Identifying objects, edges, or patterns Image Analysis : Understanding and interpreting image content Object Recognition : Detecting and identifying objects in an image What is an Image? An image is a two-dimensional function f(x, y) , where x and y are spatial coordinates, and f is the intensity (brightness or color) at that point. For digital images, both x, y, and f are finite and discrete. Types of Image Representation...