Delegating Events


L

Leslie Sanford

Say you have a class that raises an event:

public class SomeClass
{
public event EventHandler SomethingHappened;

// ...
}

And another class that uses SomeClass.

public class AnotherClass
{
private SomeClass sc = new SomeClass();

// ...
}

Say that AnotherClass raises an event just like SomeClass. In fact, it
raises this event in response to SomeClass raising its event:

public class AnotherClass
{
private SomeClass sc = new SomeClass();

public event EventHandler SomethingHappened;

public AnotherClass()
{
sc.SomethingHappened += delegate(object sender, EventArgs e)
{
OnSomethingHappened(e);
};
}

protected virtual void OnSomethingHappened(EventArgs e)
{
EventHandler handler = SomethingHappened;

if(handler != null)
{
handler(this, e);
}
}
}

Ok, it seems to me that if AnotherClass doesn't have to do anything
special in response to SomeClass raising its event, AnotherClass could
simply pass along delegates attaching to its SomethingHappened to
SomeClass's event:

public class AnotherClass
{
private SomeClass sc = new SomeClass();

public event EventHandler SomethingHappened
{
add
{
sc.SomethingHappened += value;
}
remove
{
sc.SomethingHappened -= value;
}
}

// ...
}

This seems to be a much cleaner solution. However, there is a potential
problem:

When SomeClass raises SomethingHappened, it passes itself as the sender
parameter. For clients that have attached to AnotherClass's
SomethingHappened event, they may not be expecting an object of
SomeClass's type. Worse, a private object of AnotherClass is being
exposed.

Thoughts?
 
Ad

Advertisements

J

Jon Skeet [C# MVP]

This seems to be a much cleaner solution. However, there is a potential
problem:

When SomeClass raises SomethingHappened, it passes itself as the sender
parameter. For clients that have attached to AnotherClass's
SomethingHappened event, they may not be expecting an object of
SomeClass's type. Worse, a private object of AnotherClass is being
exposed.

Thoughts?

I think it depends on what's useful at the time. In some situations,
the original object is more useful than the proxying one. In others,
it's the proxy that makes sense. You do need to make sure you document
what will be passed to a handler of the second event though. If the
original class is effectively an implementation detail, there are
encapsulation concerns - but if it's obvious that an instance of that
class is being used, and you don't mind the reference "leaking", then
it needn't be an issue.

The short version of all of the above: "it depends"!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top