ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Enterprise Application Development
    EC-332
    Progress0 / 37 topics
    Topics
    1. Overview of Enterprise Application Development: Microsoft technology history2. Introduction to .NET and its architecture3. Concept of MSIL, CLR, CLS, CTS4. Introduction to .NET framework: Managed and Unmanaged Code5. .Net Assembly6. Introduction to C# fundamentals7. Boxing and Unboxing8. Implementing multi-tier architecture9. Introduction to ADO.Net: SQL Injection, parameterized queries10. Usage of data set, Data adapter and command builder in disconnected model11. Introduction to delegate: Multicast delegates12. Introduction to windows forms13. HTML14. Introduction to javascript: javascript and its data types, variables, functions15. Debugging javascript using Firebug16. Introduction to various object models: Browser's Object (BOM), Document Object Model17. Introduction to Jquery: Jquery effects18. Introducing LINQ: LINQ to Objects, LINQ to SQL19. Query syntax, Operations (projection, filtering and join) using Linq Queries20. Introduction to ADO.NET entity framework: The entity data model, CSDL21. Eager vs lazy loading, POCO classes, DBContext API22. Querying entity data models23. Introduction to ASP.NET MVC24. MVC application structure, Controllers overview25. Action Methods, Parameterized action methods26. Introduction to razor syntax27. Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28. Data annotations, Client and Server Side Validation29. Validation and model binding, Validation and model state30. MVC Membership, Authorization and security31. Introduction to service-oriented architecture: SOAP, WSDL32. Service contract, Data contract, XML, WCF bindings33. ABC of WCF, Restful services34. Consuming rest services (CRUD operations) using Jquery AJAX and JSON35. Introduction to web API36. Example of web API using CRUD Example37. MVC routing
    EC-332›Introduction to delegate: Multicast delegates
    Enterprise Application DevelopmentTopic 11 of 37

    Introduction to delegate: Multicast delegates

    6 minread
    1,077words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,077
      Code examples0
      DifficultyIntermediate