Doing component-based development, I find myself doing this fairly often:
public class SomeClass
{
SomeOtherClass foo;
public SomeOtherClass Foo
{
get { return foo; }
set {
if (value != foo) {
if (value != null) {
// subscribe to some events
value.SomeEvent += foo_SomeEvent;
}
if (foo != null) {
// unsubscribe from subscribed events
foo.SomeEvent -= foo_SomeEvent;
}
foo = value;
}
}
}
void foo_SomeEvent(object sender, EventArgs e)
{
// do stuff
}
}
Is there any more elegant way to do this event "swapout"?
(Of course, the whole issue could be avoided if foo
was immutable, but then I wouldn't get any visual designer support.)