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.

Advertisements

About timdams
C#, .NET, Microsoft, security, .... Read more on : https://timdams.com/

One Response to Writing an event-wrapper

  1. Jan De Kock says:

    Wouldn’t extending the baseclass be easier?

    Just hide the other methods with new.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: