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.
Wouldn’t extending the baseclass be easier?
Just hide the other methods with new.
LikeLike
You have a good point but its’s not alwasy an option. What if the base class is sealed?
LikeLike