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. Wouldn’t extending the baseclass be easier?

    Just hide the other methods with new.

    Like

    1. Kostas Christodoulou december 17, 2021 — 11:47

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

      Like

Geef een reactie

Vul je gegevens in of klik op een icoon om in te loggen.

WordPress.com logo

Je reageert onder je WordPress.com account. Log uit /  Bijwerken )

Twitter-afbeelding

Je reageert onder je Twitter account. Log uit /  Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log uit /  Bijwerken )

Verbinden met %s

Deze site gebruikt Akismet om spam te bestrijden. Ontdek hoe de data van je reactie verwerkt wordt.

%d bloggers liken dit:
search previous next tag category expand menu location phone mail time cart zoom edit close