Writing an event-wrapper

A while ago, two students asked me how one could write a wrapper around around an existing class and still expose the eventhandlers therein. I didn’t had the fainted clue how to solve this. If someone would ask me how to expose properties through the wrapper the answer would straightaway be: use properties again, e.g.:

class InnerClass
{
public int SomeProp { get; set; }
}
class WrapperClass
{
private InnerClass wrappedClass = new InnerClass();
public int SomeProp{
get { return wrappedClass.SomeProp;}
set { wrappedClass.SomeProp= value;}}
}

However, what I didn’t know is that there’s basically a basically an analogue solution for this using the add/remove accessors instead of the get/set way:
class InnerClass
{
public event EventHandler SomeEvent;
}

class WrapperClass
{
private InnerClass wrappedClass = new InnerClass();
public event EventHandler SomeEvent
{
add { wrappedClass.SomeEvent += value; }
remove { wrappedClass.SomeEvent -= value; }
}
}

Voila, another important lesson learnt! More info here.

Like this tutorial? Feel free to buy my kids a fristi 

2 gedachten over “Writing an event-wrapper

  1. Jan De Kock's avatar

    Wouldn’t extending the baseclass be easier?

    Just hide the other methods with new.

    Like

    1. Kostas Christodoulou's avatar
      Kostas Christodoulou 17 december 2021 — 11:47

      You have a good point but its’s not alwasy an option. What if the base class is sealed?

      Like

Plaats een reactie

search previous next tag category expand menu location phone mail time cart zoom edit close