---
title: "Reactive Extensions (Rx) - Part 2 - Wrapping C# Events - Muhammad Rehan Saeed"
description: "Reactive Extensions IObservable wrappers for C# events and hiding the C# events entirely from subscribers using explicit interface implementations."
canonical_url: "https://rehansaeed.com/reactive-extensions-part2-wrapping-events/"
last_updated: "2014-02-13T00:00:00+00:00"
meta:
  author: "Muhammad Rehan Saeed"
  keywords: ".NET,C#,Events,Explicit Interface Implementation,INotifyPropertyChanged,Reactive Extensions,Rx"
  "og:description": "Reactive Extensions IObservable wrappers for C# events and hiding the C# events entirely from subscribers using explicit interface implementations."
  "og:image": "https://rehansaeed.com/_og/s/o_5c3afcae82e9f5cf.png"
  "og:image:alt": "Reactive Extensions (Rx) - Part 2 - Wrapping C# Events - Muhammad Rehan Saeed"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "Reactive Extensions (Rx) - Part 2 - Wrapping C# Events"
  "twitter:image": "https://rehansaeed.com/_og/s/o_5c3afcae82e9f5cf.png"
  "twitter:image:alt": "Reactive Extensions (Rx) - Part 2 - Wrapping C# Events - Muhammad Rehan Saeed"
---

> Index of every page on this site: [llms.txt](https://rehansaeed.com/llms.txt)

# [Reactive Extensions (Rx) - Part 2 - Wrapping C# Events](https://rehansaeed.com/reactive-extensions-part2-wrapping-events/)

Posted 13 February 2014 - **3 min read**

![Reactive Extensions](https://rehansaeed.com/_ipx/f_png&s_2560x1440/images/hero/Reactive-Extensions-1366x768.png)

1. [Reactive Extensions (Rx) - Replacing C# Events](https://rehansaeed.com/reactive-extensions-part1-replacing-events/)
2. [Reactive Extensions (Rx) - Wrapping C# Events](https://rehansaeed.com/reactive-extensions-part2-wrapping-events/)
3. [Reactive Extensions (Rx) - Naming Conventions](https://rehansaeed.com/reactive-extensions-part3-naming-conventions/)
4. [Reactive Extensions (Rx) - Replacing Timers](https://rehansaeed.com/reactive-extensions-part4-replacing-timers/)
5. [Reactive Extensions (Rx) - Awaiting Observables](https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/)
6. [Reactive Extensions (Rx) - Task ToObservable](https://rehansaeed.com/reactive-extensions-part6-task-toobservable/)
7. [Reactive Extensions (Rx) - Sample Events](https://rehansaeed.com/reactive-extensions-part7-sample-events/)
8. [Reactive Extensions (Rx) - Timeouts](https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/)

Sometimes it is not possible to replace a C# event with a Reactive Extensions (Rx) event entirely. This is usually because we are implementing an interface which has a C# event and we don't own the interface.

However, as I'll show in this post, its possible to create `IObservable<T>` wrappers for C# events and even to hide the C# events entirely from consumers of the class.

The method of wrapping C# events depends on the type of event handler used. Below are the three type of event handler and the method of wrapping them with an observable event.

# Wrapping an EventHandler C# Event Link to this section

The `FromEventPattern` method is used to wrap the event. Notice we have to specify delegates for subscribing (`+=`) and unsubscribing (`-=`) to the event.

```cs
public event EventHandler BunnyRabbitsAttack;

public IObservable<object> WhenBunnyRabbitsAttack
{
    get
    {
        return Observable
            .FromEventPattern(
                h => this.BunnyRabbitsAttack += h,
                h => this.BunnyRabbitsAttack -= h);
    }
}
```

# Wrapping an EventHandler C# Event Link to this section

This example is much the same as the last, except we have to deal with the event arguments. The `FromEventPattern` method returns an `EventPattern<T>` object, which contains the sender and the event arguments. We're only interested in the contents of the event arguments, so we use a Select to return just the `BunnyRabbits` property.

```cs
public event EventHandler<BunnyRabbitsEventArgs> BunnyRabbitsAttack;

public IObservable<BunnyRabbits> WhenBunnyRabbitsAttack
{
    get
    {
        return Observable
            .FromEventPattern<BunnyRabbitsEventArgs>(
                h => this.BunnyRabbitsAttack += h,
                h => this.BunnyRabbitsAttack -= h)
            .Select(x => x.EventArgs.BunnyRabbits);
    }
}
```

# Wrapping a Custom Event Handler C# Event Link to this section

Some C# events use a custom event handler. In this case we have to specify the type of the event handler as a generic argument in the `FromEventPattern` method.

```cs
public event BunnyRabbitsEventHandler BunnyRabbitsAttack;

public IObservable<BunnyRabbits> WhenBunnyRabbitsAttack
{
    get
    {
        return Observable
            .FromEventPattern<BunnyRabbitsEventHandler, BunnyRabbitsEventArgs>(
                h => this.BunnyRabbitsAttack += h,
                h => this.BunnyRabbitsAttack -= h)
            .Select(x => x.EventArgs.BunnyRabbits);
    }
}
```

# Hiding Existing Events Using Explicit Interface Implementation Link to this section

The disadvantage of the above approach is that we now have two ways to access our event. One with the old style C# event and the other with our new Reactive Extensions event. With a bit of trickery we can hide the C# event in some cases.

The `INotifyPropertyChanged` interface is very commonly used by XAML developers. It has a single event called `PropertyChanged`. To hide the `PropertyChanged` C# event we can explicitly implement the interface (Click [here](http://stackoverflow.com/questions/143405/c-sharp-interfaces-implicit-implementation-versus-explicit-implementation) for details on implicit versus explicit implementations of interfaces). Secondly, we wrap the event as we did before.

Now the `PropertyChanged` C# event can only be accessed by first casting the object to `INotifyPropertyChanged` (Binding in XAML languages, which uses this interface continues to work). Our new Reactive Extensions observable event is now the default method of subscribing for property changed events.

```cs
public abstract class NotifyPropertyChanges : INotifyPropertyChanged
{
    event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
    {
        add { this.propertyChanged += value; }
        remove { this.propertyChanged -= value; }
    }

    private event PropertyChangedEventHandler propertyChanged;

    public IObservable<string> WhenPropertyChanged
    {
        get
        {
            return Observable
                .FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                    h => this.propertyChanged += h,
                    h => this.propertyChanged -= h)
                .Select(x => x.EventArgs.PropertyName);
        }
    }

    protected void OnPropertyChanged(string propertyName) =>
        this.propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
```

# Summing Up Link to this section

So it may not always be possible to get rid of, dare I say it legacy C# events but we can certainly wrap them with Reactive Extension observables and even hide them altogether.

## Web Mentions

[What's this?](https://en.wikipedia.org/wiki/Webmention)

### 0 Linked

### 0 Replies

## GitHub Comments

### 4 Comments

[Comment on GitHub](https://github.com/RehanSaeed/rehansaeed.github.io/issues/104)

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Davide Cologni](https://camo.githubusercontent.com/d221221ebf2729d82bd1b515b68b86c90406f1ba048e187df6b4fa3f4ae08be5/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f38353263366261353438626265633533626335396539353762386566626330373f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/d221221ebf2729d82bd1b515b68b86c90406f1ba048e187df6b4fa3f4ae08be5/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f38353263366261353438626265633533626335396539353762386566626330373f733d393626643d6d6d26723d67) **Davide Cologni** commented on **2018-01-02 22:25:55**

Hi I found this tutorial very useful, I want suggest to use the dot conditional operator (?.) in the protected method that wrap event wo explicit checking if handler is null in this way:

```
this.propertyChange?.Invoke(this, new EventArgsBlaBla());
```

With expression body function is very concise and elegant :^)

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2018-01-03 10:20:00**

> Hi I found this tutorial very useful, I want suggest to use the dot conditional operator (?.) in the protected method that wrap event wo explicit checking if handler is null in this way:
>
> ```
> this.propertyChange?.Invoke(this, new EventArgsBlaBla());
> ```
>
> With expression body function is very concise and elegant :^)

I wrote the blog post before the null conditional operator was available but I've now updated the post, thanks!

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![George Papadopoulos](https://camo.githubusercontent.com/f2103ab6671eb6501b99bd72be3845379caed246e97f50fab13b090a081f6af9/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f64636136393038636134613038623963303930393930613039343334363330353f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/f2103ab6671eb6501b99bd72be3845379caed246e97f50fab13b090a081f6af9/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f64636136393038636134613038623963303930393930613039343334363330353f733d393626643d6d6d26723d67) **George Papadopoulos** commented on **2019-03-06 21:40:11**

Hi there, is it possible to give us an example of how the abstract class `NotifyPropertyChanges` is used? Thanks In advance.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2019-03-08 10:02:44**

> Hi there, is it possible to give us an example of how the abstract class `NotifyPropertyChanges` is used? Thanks In advance.

I wrote a series of blog posts you can look at [here](https://rehansaeed.com/model-view-viewmodel-mvvm-part1-overview/).

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://rehansaeed.com/#website","@type":"WebSite","description":"Software Developer at Microsoft, YouTuber, Open Source Contributor and Blogger","inLanguage":"en-GB","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/","author":{"@id":"https://rehansaeed.com/#identity"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://rehansaeed.com/?search={search_term_string}"},"query-input":"required name=search_term_string"}],"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/reactive-extensions-part2-wrapping-events/#webpage","@type":"WebPage","dateModified":"2014-02-13T00:00:00+00:00","datePublished":"2014-02-13T00:00:00+00:00","description":"Reactive Extensions IObservable wrappers for C# events and hiding the C# events entirely from subscribers using explicit interface implementations.","name":"Reactive Extensions (Rx) - Part 2 - Wrapping C# Events","url":"https://rehansaeed.com/reactive-extensions-part2-wrapping-events/","breadcrumb":{"@id":"https://rehansaeed.com/reactive-extensions-part2-wrapping-events/#breadcrumb"},"isPartOf":{"@id":"https://rehansaeed.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://rehansaeed.com/reactive-extensions-part2-wrapping-events/"]}]},{"@id":"https://rehansaeed.com/#identity","@type":"Person","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/about/","image":{"@id":"https://rehansaeed.com/#/schema/image/1"},"sameAs":["https://github.com/RehanSaeed","https://www.linkedin.com/in/muhammad-rehan-saeed","https://stackoverflow.com/users/1212017/muhammad-rehan-saeed","https://www.youtube.com/c/MuhammadRehanSaeed","https://www.twitch.tv/rehansaeeduk"]},{"@id":"https://rehansaeed.com/#publisher","@type":"Organization","logo":"https://rehansaeed.com/images/schema/Publisher-600x60.png","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com"},{"@id":"https://rehansaeed.com/reactive-extensions-part2-wrapping-events/#article","@type":"Article","dateModified":"2014-02-13T00:00:00+00:00","datePublished":"2014-02-13T00:00:00+00:00","description":"Reactive Extensions IObservable wrappers for C# events and hiding the C# events entirely from subscribers using explicit interface implementations.","headline":"Reactive Extensions (Rx) - Part 2 - Wrapping C# Events","inLanguage":"en-GB","url":"https://rehansaeed.com/reactive-extensions-part2-wrapping-events/","author":{"@id":"https://rehansaeed.com/#identity"},"image":[{"@type":"ImageObject","url":"https://rehansaeed.com/images/hero/Reactive-Extensions-1366x768.png","caption":"Reactive Extensions","width":"1366","height":"768"}],"isPartOf":{"@id":"https://rehansaeed.com/reactive-extensions-part2-wrapping-events/#webpage"},"keywords":[".NET","C#","Events","Explicit Interface Implementation","INotifyPropertyChanged","Reactive Extensions","Rx"],"mainEntityOfPage":{"@id":"https://rehansaeed.com/reactive-extensions-part2-wrapping-events/#webpage"},"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/reactive-extensions-part2-wrapping-events/#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Blog","item":"https://rehansaeed.com/","position":1},{"@type":"ListItem","name":"Reactive Extensions (Rx) - Part 2 - Wrapping C# Events","item":"https://rehansaeed.com/reactive-extensions-part2-wrapping-events/","position":2}]},{"@id":"https://rehansaeed.com/#/schema/image/1","@type":"ImageObject","contentUrl":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png","inLanguage":"en-GB","url":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png"}]}
```

## Sitemap

See the full [sitemap](https://rehansaeed.com/sitemap.md) for all pages.
