📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • The Problem
  • Setting Up a Publisher
  • Setting Up a Subscriber
  • Passing custom args to EventArgs
  • EventHandler Delegate
  1. Csharp
  2. C Sharp Advanced

Events

The Problem

Events are mechanism by which to communicate between objects. In particular, one object acts as a publisher that sends an event, while the other other acts as a subscriber receiving the event.

The major benefit of events is it makes applications more loosely coupled.

Imagine we have a video encoder where we want to send an email after the encoding is complete. In normal cases, you will use dependency injection to insert services into your VideoEncoder class:

public class VideoEncoder
{
    public void Encode(Video video)
    {
        // Encoding logic...

        _mailService.Send(new Mail());
    }
}

This code is generally fine. However, the problem arises when we have to add another service:

_messageService.Send(new Text());

Problem: Adding another service means that VideoEncoder and all classes that inherit from or use VideoEncoder must be recompiled! Additionally, if we mess up our new logic, it could break in every place where VideoEncoder is used.

Setting Up a Publisher

To solve the above problem, we don't dependency inject anything into VideoEncoder. It has no awareness of MailService or MessageService.

Instead, VideoEncoder, as a publisher, just needs to do the following:

  1. Define a delegate

  2. Define an event based on that delegate

  3. Raise the event

public class VideoEncoder
{
    // 1. Define a delegate
    public delegate void VideoEncodedEventHandler(object source, EventArgs e);

    // 2. Define an event based on that delegate
    public event VideoEncodedEventHandler VideoEncoded;

    public void Encode(Video video)
    {
        // Encoding logic...

        // 3. Raise the event
        OnVideoEncoded();
    }

    // Note: this is an event-raising method
    // Checks to see if there are subscribers BEFORE invoking
    protected virtual void OnVideoEncoded()
    {
        if (VideoEncoded != null)
            VideoEncoded(this, EventArgs.Empty); // we don't pass any args
    }
}

Things to note:

  • We use a delegate to set a contract between publisher and subscriber. You'll see later that the subscriber must adhere to the signature of the delegate.

  • The convention for a delegate used for an event is to name it <EventName>EventHandler.

  • The convention for an event-raising method is to name it On<EventName>.

  • The best practice for event-raising methods is to apply the access modifiers protected and virtual.

Setting Up a Subscriber

Now that we have a publisher set up, we need to make sure the MailService and MessageService classes subscribe to the event.

The process is exactly like storing methods in a delegate:

  1. Define a method that matches the signature of the delegate

  2. Add the method to the event

// Same code applies to MessageService...
public class MailService
{
    // 1. Define a method that matches the signature of the delegate
    public void OnVideoEncoded(object source, EventArgs e)
    {
        // Send mail...
    }
}


var video = new Video();
var encoder = new VideoEncoder();

// 2. Add methods to the event
var mailService = new MailService();
var messageService = new MessageService();
encoder.VideoEncoded += mailService.VideoEncoded;
encoder.VideoEncoded += messageService.VideoEncoded;

encoder.Encode(video);

That's it! Now MailService and MessageService will work after the video finishes encoding.

Passing custom args to EventArgs

Suppose that we want our subscribers to get access to the video that was just encoded. To do this, we need to expand on EventArgs, so we can pass video to the subscriber.

public class VideoEventArgs : EventArgs
{
    public Video Video { get; set; }
}

public class VideoEncoder
{
    public delegate void VideoEncodedEventHandler(object source, VideoEventArgs e);

    public event VideoEncodedEventHandler VideoEncoded;

    public void Encode(Video video)
    {
        // Encoding logic...

        OnVideoEncoded(video);
    }

    protected virtual void OnVideoEncoded(Video video)
    {
        if (VideoEncoded != null)
            // Now the event can include `video`!
            VideoEncoded(this, new VideoEventArgs() { Video = video });
    }
}

// And the subscriber can now access `Video`!
public class MailService
{
    public void OnVideoEncoded(object source, VideoEventArgs e)
    {
        Console.WriteLine(e.Video.Title);
    }
}

EventHandler Delegate

Instead of defining our own custom VideoEncodedEventHandler delegate, .NET framework now provides the built-in EventHandler delegate.

  • EventHandler is a delegate with a return type of void and parameters object source and EventArgs e.

  • EventHandler<TEventArgs> is the same delegate except you pass your own custom event args.

Here's how the code looks:

public class VideoEncoder
{
    public event EventHandler<VideoEventArgs> VideoEncoded;

    // ...
}
PreviousLambda ExpressionsNextC Sharp Fundamentals

Last updated 3 years ago