ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalEC-332Csharp Delegates
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    EC-332

    Enterprise Application Development

    Progress0 / 37 done
    Topics37
    1Microsoft technology history2Introduction to .NET and its architecture3Concept of MSIL, CLR, CLS, CTS
    4Managed and Unmanaged Code5.Net Assembly6Introduction to C# fundamentals7Boxing and Unboxing8Implementing multi-tier architecture
    9SQL Injection, parameterized queries10Usage of data set, Data adapter and command builder in disconnected model
    11Multicast delegates12Introduction to windows forms13HTML
    14javascript and its data types, variables, functions15Debugging javascript using Firebug
    16Browser's Object (BOM), Document Object Model
    17Jquery effects
    18LINQ to Objects, LINQ to SQL19Query syntax, Operations (projection, filtering and join) using Linq Queries
    20The entity data model, CSDL21Eager vs lazy loading, POCO classes, DBContext API22Querying entity data models23Introduction to ASP.NET MVC24MVC application structure, Controllers overview25Action Methods, Parameterized action methods26Introduction to razor syntax27Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28Data annotations, Client and Server Side Validation29Validation and model binding, Validation and model state30MVC Membership, Authorization and security
    31SOAP, WSDL32Service contract, Data contract, XML, WCF bindings33ABC of WCF, Restful services34Consuming rest services (CRUD operations) using Jquery AJAX and JSON35Introduction to web API36Example of web API using CRUD Example37MVC routing
    6 min read
    Topic 11 of 37
    Topic Study Note Illustration
    11

    Introduction to delegate: Multicast delegates

    In C#, a delegate is a type-safe reference to a method. It can be thought of as a pointer to a method. Delegates allow methods to be...

    Introduction to Delegates

    In C#, a delegate is a type-safe reference to a method. It can be thought of as a pointer to a method. Delegates allow methods to be passed as parameters, and they enable flexible and dynamic method invocation. They are similar to function pointers in C and C++, but are type-safe and object-oriented in C#.

    Key Characteristics of Delegates:

    • Type-safe: Delegates ensure that the method signatures match.
    • Encapsulation: Delegates allow methods to be encapsulated and passed around like objects.
    • Flexibility: They enable callback mechanisms, event handling, and passing methods as arguments.

    A delegate can point to a single method or multiple methods (in the case of multicast delegates).

    Syntax of a Delegate:

    To declare a delegate, we need to specify its signature, which includes the return type and parameters of the method it can reference. Here's a basic example:

    public delegate void MyDelegate(string message); // Delegate declaration
    

    In this case, MyDelegate is a delegate type that points to methods with the signature void MethodName(string message).

    Creating a Delegate Instance:

    To create a delegate instance, we associate it with a method that matches its signature:

    class Program
    {
        public static void PrintMessage(string message)
        {
            Console.WriteLine(message);
        }
    
        static void Main()
        {
            // Create a delegate instance pointing to PrintMessage method
            MyDelegate del = new MyDelegate(PrintMessage);
    
            // Invoke the delegate
            del("Hello, World!");  // Output: Hello, World!
        }
    }
    

    Multicast Delegates

    A multicast delegate is a delegate that can reference more than one method at the same time. When the multicast delegate is invoked, it calls each method in the list of methods in order, and passes the result from the last invoked method (in the case of void methods, they just execute in order without returning a value).

    How Multicast Delegates Work:

    1. Combining Delegates: You can add methods to a delegate using the += operator.
    2. Removing Methods: You can remove methods using the -= operator.
    3. Invocation: When the multicast delegate is invoked, it calls all the methods in the invocation list in the order they were added.

    Example of Multicast Delegate:

    using System;
    
    public delegate void MyDelegate(string message); // Delegate declaration
    
    class Program
    {
        public static void Method1(string message)
        {
            Console.WriteLine("Method1: " + message);
        }
    
        public static void Method2(string message)
        {
            Console.WriteLine("Method2: " + message);
        }
    
        static void Main()
        {
            // Create a delegate instance
            MyDelegate del = new MyDelegate(Method1);
    
            // Add Method2 to the delegate invocation list
            del += Method2;
    
            // Invoke the delegate
            del("Hello, Multicast!");  
            // Output:
            // Method1: Hello, Multicast!
            // Method2: Hello, Multicast!
        }
    }
    

    In this example:

    • The delegate del points to Method1 initially.
    • Method2 is added to the invocation list using the += operator.
    • When the delegate is invoked (del("Hello, Multicast!")), it calls both Method1 and Method2.

    Important Points About Multicast Delegates:

    1. Order of Invocation: The methods are called in the order in which they are added to the delegate's invocation list.

    2. Return Values: If the methods in the delegate have a return value, only the return value of the last method in the invocation list is returned. This is because the return value of a delegate invocation is overwritten with the return value of the last invoked method.

      // Example with return values
      public delegate int MyIntDelegate(int number);
      
      public static int AddTen(int number) => number + 10;
      public static int MultiplyByTwo(int number) => number * 2;
      
      static void Main()
      {
          MyIntDelegate del = AddTen;
          del += MultiplyByTwo;
      
          // Only MultiplyByTwo's result (20) will be returned, because it is last
          Console.WriteLine(del(5));  // Output: 20
      }
      
    3. Return Type of Multicast Delegates: For multicast delegates, the return type must be void if you expect all methods to execute without returning a value, as shown in the first multicast example. If the return type is non-void, only the result of the last method in the chain is returned.

    4. Handling Exceptions: If an exception is thrown by one of the methods in a multicast delegate, the remaining methods will not be called. This can be managed by handling exceptions within each method.

    Removing Methods from the Invocation List:

    If you no longer want to call a method, you can remove it from the multicast delegate using the -= operator:

    del -= Method2;  // Remove Method2 from the delegate
    

    After removing Method2, if you invoke del, only Method1 will be called.

    Practical Use Case: Event Handling

    One of the most common uses of multicast delegates in C# is event handling. In event-driven programming, an event is often handled by multiple methods, and each handler can be added to a delegate (the event).

    Here's a quick example of how a multicast delegate is used with events:

    using System;
    
    public delegate void Notify();  // Define a delegate for the event
    
    public class EventPublisher
    {
        public event Notify OnNotify;
    
        public void TriggerEvent()
        {
            OnNotify?.Invoke();  // Trigger the event (multicast delegate in action)
        }
    }
    
    public class Subscriber
    {
        public void Handler1()
        {
            Console.WriteLine("Handler1 is called.");
        }
    
        public void Handler2()
        {
            Console.WriteLine("Handler2 is called.");
        }
    }
    
    class Program
    {
        static void Main()
        {
            EventPublisher publisher = new EventPublisher();
            Subscriber subscriber = new Subscriber();
    
            // Subscribing methods to the event
            publisher.OnNotify += subscriber.Handler1;
            publisher.OnNotify += subscriber.Handler2;
    
            // Trigger the event
            publisher.TriggerEvent();  // Both handlers are called
            // Output:
            // Handler1 is called.
            // Handler2 is called.
        }
    }
    

    In this example:

    • The OnNotify event uses a multicast delegate Notify.
    • Multiple handlers (Handler1 and Handler2) are subscribed to the event.
    • When the event is triggered (publisher.TriggerEvent()), both handlers are invoked.

    Conclusion

    • Delegates in C# provide a type-safe mechanism for referencing methods and allow methods to be passed as parameters.
    • Multicast Delegates are a special type of delegate that can reference multiple methods. They are invoked in the order they are added, and only the return value of the last method is returned if the delegate has a return type.
    • Multicast Delegates are commonly used in event handling, where multiple methods (event handlers) can be attached to an event and executed in sequence.

    This powerful feature makes delegates and multicast delegates an essential part of C# programming, especially for event-driven applications.

    ← Previous topic 10
    Usage of data set, Data adapter and command builder in disconnected model
    Next topic 12 →
    Introduction to windows forms

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    6mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Enterprise Application Development