You have several options.
1) Create an event
in CarClass and capture it in MyGames.
2) Use a delegate
and pass the function reference to CarClass object
3) Add a property to CarClass of type MyGames (say called "Owner"), and after you create CarClass, assign "this" to it: myCar.Owner=this
. So you've created a reference in the CarClass object to its creator, and code in CarClass can directly access the methods of its owner.
Which is the best depends on the situation and how these objects will be used. An event is probably preferred, since it offers the most flexibility. A delegate is less flexible and more efficient than an event, though they really serve slightly different purposes. (An event is really an extension of a delegate). The last one is probably the worst form, generally, since it tightly binds the objects, but it has a time and place.
Here's #1
public class CarClass
{
// A delegate is a pointer to a function. Events are really a way of late
// binding delegates, so you need to one of these first to have an event.
public delegate void ExplodedHandler(CarClass sender);
// an event is a construct which is used to pass a delegate to another object
// You create an event based for a delegate, and capture it by
// assigning the function reference to it after the object is created.
public event ExplodedHandler Exploded;
protected void CarCrash()
{
... do local stuff
// Make sure ref exists before calling; if its required that something
// outside this object always happen as a result of the crash then
// handle the other case too (throw an error, e.g.)/
// See comments below for explanation of the need to copy the event ref
// before testing against null
ExplodedHandler tempEvent = Exploded;
if (tempEvent != null) {
tempEvent(this);
}
}
}
public class MyGames
{
...
...
CarClass myCar = new CarClass(...);
myCar.Exploded += new ExplodedHandler(GameOver);
Main () {
MyGames game = MyGames(...);
}
void GameOver(CarClass sender) {
// Do stuff
}
}