There are two ways to do this.
Pass the parent object to the child object and call a method on the parent.
public class MyForm : Form
{
private MyWorker _worker;
public MyForm()
{
_worker = new MyWorker();
}
public void PassMessage(string message)
{
}
}
public class MyWorker
{
private Form _form;
public MyWorker(Form form)
{
_form = form;
}
public void doWork()
{
_form.PassMessage("My message");
}
}
Passing in the parent object as a form irreversibly links the child component to a form. You could create an interface to allow the worker to become reusable.
public interface IMessageProcessor
{
void SendMessage(string message);
}
public class MyForm : Form, IMessageProcessor
{
private MyWorker _worker;
public MyForm()
{
_worker = new MyWorker();
}
public void PassMessage(string message)
{
}
}
public class MyWorker
{
private IMessageProcessor _messageProcessor;
public MyWorker(IMessageProcessor messageProcessor)
{
_messageProcessor = messageProcessor;
}
public void doWork()
{
_messageProcessor.PassMessage("My message");
}
}
Using interface/abstract classes in this way is a technique called inversion of control, or IOC, sometimes also known as dependency injection.
Another way is to use events. The child object has an event which bubbles the message back up to the parent class.
public class MyForm : Form
{
private MyWorker _worker;
public MyForm()
{
_worker = new MyWorker();
_worker.OnNewMessage += new MyWorker.NewMessageHandler(_worker_OnNewMessage);
}
public void _worker_OnNewMessage(string message)
{
}
}
public class MyWorker
{
public delegate void NewMessageHander(string message);
public event NewMessageHander OnNewMessage;
public void doWork()
{
if(OnNewMessage != null)
OnNewMessage("My message");
}
}