ASP.NET

C# | Delegates

C# | Delegates

C# | Delegates

A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.


KeyPoints About Delegates:
1. Provides a good way to encapsulate the methods.
2. Delegates are the library class in System namespace.
3. These are the type-safe pointer of any method.
4. Delegates are mainly used in implementing the call-back methods and events.
5. Delegates can be chained together as two or more methods can be called on a single event.
6. It doesn’t care about the class of the object that it references.
7. Delegates can also be used in “anonymous methods” invocation.
8. Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled to delegate types in certain contexts. Sometimes, these features together are known as anonymous functions.



Declaration of Delegates (Single Cast Delegate)
Step 1 Declare : Delegate type can be declared using the delegate keyword.
Step 2 Refer Method:
Once a delegate is declared, delegate instance will refer and call those methods whose return type and parameter-list matches with the delegate declaration.


[modifier] delegate [return_type] [delegate_name] ([parameter_list]);

/*
    modifier: It is the required modifier which defines the access of delegate and it is optional to use.
    delegate: It is the keyword which is used to define the delegate.
    return_type: It is the type of value returned by the methods which the delegate will be going to call. It can be void. A method must have the same return type as the delegate.
    delegate_name: It is the user-defined name or identifier for the delegate.
    parameter_list: This contains the parameters which are required by the method when called through the delegate.
*/



Complete Example (Single Cast Delegate)

class TheTechFoyer {
     
    // Declaring the delegates
    // Here return type and parameter type should be same as the return type and parameter type of the two methods
    // "addnumber" and "subnumber" are two delegate names
    public delegate void addnumber(int a, int b);
    public delegate void subnumber(int a, int b);
       
    // method "sum"
    public void sum(int a, int b)
    {
        Console.WriteLine("(100 + 50) = {0}", a + b);
    }

    // method "subtract"
    public void subtract(int a, int b)
    {
        Console.WriteLine("(100 - 80) = {0}", a - b);
    }
   
    // Main Method
    public static void Main(String []args)
    {        
        // creating object
        TheTechFoyer obj = new TheTechFoyer();
           
        // creating object of delegate, for method "sum" & instantiating the delegates
        addnumber del_sum = new addnumber(obj.sum);

        // creating object of delegate, for method "subtract" & instantiating the delegates
        subnumber del_subtract = new subnumber(obj.subtract);
   
        // pass the values to the methods using respective delegate object(s)
        del_sum(100, 50);
        del_subtract(100, 80);
   
        // OR can be written as using "Invoke" method
        // del_sum.Invoke(100, 50);
        // del_subtract.Invoke(100, 80);
    }
}





Multicasting of a Delegate
Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single Cast Delegate). It helps the user to point more than one method in a single call.

Properties of Multicasting:
Delegates are combined and when you call a delegate then a complete list of methods is called.
All methods are called in First in First Out(FIFO) order.
+ or += Operator is used to add the methods to delegates.
– or -= Operator is used to remove the methods from the delegates list.

Multicasting of delegate should have a return type of Void otherwise it will throw a runtime exception. Also, the multicasting of delegate will return the value only from the last method added in the multicast. Although, the other methods will be executed successfully.

class rectangle {
     
    // declaring delegate
    public delegate void rectDelegate(double height, double width);
 
    // "area" method
    public void area(double height, double width){
        Console.WriteLine("Area is: {0}", (width * height));
    }
 
    // "perimeter" method
    public void perimeter(double height, double width){
        Console.WriteLine("Perimeter is: {0} ", 2 * (width + height));
    }
 
 
    // Main Method
    public static void Main(String []args)
    {
       
        // creating object of class "rectangle"
        rectangle rect = new rectangle();    
   
        // creating delegate object, and pass the method as parameter by class object "rect"
        rectDelegate rectdele = new rectDelegate(rect.area);
        // OR can be written as
        rectDelegate rectdele = rect.area;

       
        // Multicasting 2nd method "perimeter", with the same object
        rectdele += rect.perimeter;
   
        // pass the values in both method by using "Invoke" method
        rectdele.Invoke(1.5, 2.5);
        Console.WriteLine();    
    }
}

// Output is
Area is: 3.75
Perimeter is: 8







Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram