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
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Introduction to Events
    Advanced ProgrammingTopic 2 of 55

    Introduction to Events

    7 minread
    1,122words
    Intermediatelevel

    Introduction to Events in C#

    In C#, events are a fundamental part of the event-driven programming model, allowing applications to respond to user actions or system-generated notifications. Events are key components in GUI programming (like in Windows Forms or WPF), but they are also widely used in any program where certain actions trigger a response, such as data changes, button clicks, or file system updates.

    Events are a way to enable communication between objects: an object can signal that something has happened (an event), and other objects can listen for these signals (event handlers) and react accordingly.

    What is an Event?

    An event is a message sent by an object to signal that something important has occurred. The object that sends the event is called the event sender (or publisher), and the object that listens for the event and responds to it is called the event listener (or subscriber).

    In C#, events are typically used in conjunction with delegates (which are references to methods) and allow for a flexible mechanism of invoking multiple methods when an event is raised.

    Key Concepts

    1. Event: A way for a class or object to notify other classes or objects that something has occurred (e.g., a button has been clicked).
    2. Delegate: A type that defines the method signature for event handlers. It specifies the return type and parameters that event handler methods must have.
    3. Event Handler: A method that handles an event. It is a method that is called when an event is raised.
    4. Publisher/Subscriber: The publisher raises events, and the subscriber (the event handler) listens for and reacts to these events.

    1. Event Declaration

    In C#, events are typically declared within a class or object that wants to notify others when something occurs.

    An event is declared using the event keyword, followed by a delegate type. For example, the delegate type can be EventHandler or any custom delegate type.

    Syntax:

    public event EventHandler MyEvent;
    

    In this case, EventHandler is a predefined delegate type in .NET that is used for events that do not require parameters (other than the sender object and event arguments).

    2. Event Handler

    An event handler is a method that responds to the event. The method signature must match the delegate type used for the event.

    For example, if the event uses the EventHandler delegate (which has a signature void Handler(object sender, EventArgs e)), the event handler should look like this:

    private void MyEventHandler(object sender, EventArgs e)
    {
        Console.WriteLine("Event has occurred!");
    }
    

    3. Raising an Event

    An event is raised (or triggered) by calling the event delegate. In C#, events are usually raised inside the class that defines the event. The ?.Invoke syntax ensures that the event only triggers if there are any subscribers (event listeners) attached.

    Syntax for raising an event:

    if (MyEvent != null)
    {
        MyEvent(this, EventArgs.Empty);
    }
    

    Or using the shorthand with ?.Invoke:

    MyEvent?.Invoke(this, EventArgs.Empty);
    

    4. Subscribing to an Event

    To react to an event, a method needs to subscribe to the event. This is done by attaching an event handler to the event.

    Syntax for subscribing:

    MyEvent += new EventHandler(MyEventHandler);
    

    This adds the MyEventHandler method to the list of event handlers that will be called when the event is raised.

    5. Unsubscribing from an Event

    If you no longer want to listen for an event, you can unsubscribe from it. Unsubscribing is done using the -= operator.

    Syntax for unsubscribing:

    MyEvent -= new EventHandler(MyEventHandler);
    

    6. Custom Event Arguments

    In many cases, you may need to pass additional information when an event is raised. To do this, you can create a custom EventArgs class that extends EventArgs to include the extra data.

    Example:

    // Define custom event arguments
    public class MyEventArgs : EventArgs
    {
        public int Value { get; set; }
    
        public MyEventArgs(int value)
        {
            Value = value;
        }
    }
    
    // Define an event with custom EventArgs
    public event EventHandler<MyEventArgs> MyCustomEvent;
    

    Then, when raising the event, you pass an instance of MyEventArgs:

    MyCustomEvent?.Invoke(this, new MyEventArgs(42));
    

    7. Event Example

    Let’s walk through a basic example of using events in C#.

    using System;
    
    public class Button
    {
        // Declare an event
        public event EventHandler Click;
    
        // Method to raise the event
        public void OnClick()
        {
            Console.WriteLine("Button clicked.");
            Click?.Invoke(this, EventArgs.Empty);  // Raise the event
        }
    }
    
    public class Program
    {
        // Event handler
        private static void ButtonClickHandler(object sender, EventArgs e)
        {
            Console.WriteLine("Button click event handled.");
        }
    
        public static void Main()
        {
            // Create a Button object
            Button button = new Button();
    
            // Subscribe to the event
            button.Click += ButtonClickHandler;
    
            // Simulate a button click
            button.OnClick();  // This will trigger the event
        }
    }
    

    Output:

    Button clicked.
    Button click event handled.
    

    In this example:

    1. The Button class declares an event Click.
    2. The OnClick method raises the Click event.
    3. The ButtonClickHandler method is an event handler that handles the Click event.
    4. The event handler is subscribed to the Click event in the Main method.
    5. When OnClick is called, the event is raised, and the event handler is triggered.

    8. Multicast Delegates

    In C#, an event can have multiple subscribers (event handlers). These handlers are invoked in the order they were added to the event. This is possible because events in C# are built on multicast delegates, which allow multiple methods to be called when an event is triggered.

    9. Best Practices for Events in C#

    • Encapsulation: It's common to make event fields private and provide a method for raising the event. This prevents external code from directly invoking the event.

    • Event Naming Convention: It's a good practice to name events with the "Event" suffix (e.g., ButtonClickEvent), although it's not required.

    • Use EventArgs: When creating custom events, always use a subclass of EventArgs to pass any data, even if it's just a placeholder.

    • Unsubscribing from Events: It's essential to unsubscribe from events when they are no longer needed to prevent memory leaks. This is especially important in GUI applications where controls may be disposed of, but the event handlers are still subscribed.

    Conclusion

    In C#, events are a crucial part of the language’s support for event-driven programming. They allow classes to notify other classes when something happens, without requiring a direct connection between them. By using delegates and event handlers, you can create flexible, scalable systems where one object can broadcast notifications to many listeners. Events are widely used in GUI programming, in systems that involve asynchronous operations, and wherever multiple objects need to respond to a shared action or change.

    Previous topic 1
    Visual Programming Basics
    Next topic 3
    Fundamentals of Event-Driven Programming

    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 time7 min
      Word count1,122
      Code examples0
      DifficultyIntermediate