Communication from child to parent in using Events/Delegates

U

uupi_duu

Hello,

I have a parent class which creates and uses child class. Child class
use it's own methods for different tasks.
If an error occurs in child classes methods I would like to inform it
to parent class using Events/Delegates.
What would be a nicest way to child to communicate to parent using
Events or Delegates?

Sample would be nice,

Thanks!
 
M

Marc Gravell

If an error occurs in child classes methods I would like to inform it
to parent class using Events/Delegates.
Well, the norm would be to inform the *caller* by throwing an
exception; however, you could easily also notify the parent. If the
child and parent are pretty fixed, and if a child only has one parent,
then I wouldn't use events - I would use a direct call from child to
parent; this should involve a lot less objects and mess.

However, if you want to be able to hear about problems into multiple /
disparate classes, then events may be suitable. The following
illustrates both approaches; if the method fails, the parent gets
told.

class ChildCollection : Collection<Child>
{
protected override void InsertItem(int index, Child item)
{
Attach(this[index]);
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
Detatch(this[index]);
base.RemoveItem(index);
}
protected override void SetItem(int index, Child item)
{
Detatch(item);
Attach(item);
base.SetItem(index, item);
}
private void Attach(Child child)
{
if (child != null)
{
child.Error += child_Error;
child.SetParent(this);
}
}
private void Detatch(Child child)
{
if (child != null)
{
child.Error -= child_Error;
child.SetParent(null);
}
}

void child_Error(object sender, ExceptionEventArgs e)
{
// event approach
}
internal void ChildError(Child child, Exception exception)
{
// invoke approach
}
}

class Child
{
private ChildCollection parent;
internal void SetParent(ChildCollection newParent)
{
if (!ReferenceEquals(parent, newParent)
&& parent != null) throw new
InvalidOperationException("Only one parent at a time");
parent = newParent;
}
public event EventHandler<ExceptionEventArgs> Error;
protected void OnError(Exception exception)
{
// using event
EventHandler<ExceptionEventArgs> handler = Error;
if (handler != null) handler(this, new
ExceptionEventArgs(exception));
// using invoke
if (parent != null) parent.ChildError(this, exception);
}
public void SomeMethod()
{
try
{
throw new InvalidOperationException("It went wrong");
}
catch (Exception ex)
{
OnError(ex);
throw;
}
}
}
[ImmutableObject(true)]
public sealed class ExceptionEventArgs : EventArgs
{
public readonly Exception Exception;
public ExceptionEventArgs(Exception exception)
{
Exception = exception;
}
}
 

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