Well you certainly can't do it without changing code in either class (assuming you also don't want to change everywhere that calls class1.Execute
) - at least not without some deep code-weaving/instrumentation magic. However, you can fairly easily add an event in Class1
:
public class Class1
{
// TODO: Think of a better name :)
public event EventHandler ExecuteCalled = delegate {};
public void Execute()
{
ExecuteCalled(this, EventArgs.Empty);
// Do your normal stuff
}
}
The delegate{}
bit is just to make sure that there's always at least a no-op event handler registered - it means you don't need to check for nullity.
You'd then hook it up by writing:
Class1 class1 = new Class1();
Logger logger = new Logger();
class1.ExecuteCalled += (sender, args) => logger.Write(sender.ToString());
(This is assuming you're using C# 3 so you have lambda expressions available to you - let me know if that's not the case.)
If Class1
implements an interface (say IFoo
), you might want to write an implementation of the interface which wraps another implementation, and just logs before each call:
public sealed class LoggingFoo : IFoo
{
private readonly IFoo original;
private readonly IFoo logger;
public LoggingFoo(IFoo original, Logger logger)
{
// TODO: Check arguments for nullity
this.original = original;
this.logger = logger;
}
// Implement IFoo
public void Execute()
{
logger.Write("Calling Execute on {0}", original);
original.Execute();
}
}
Then just use that wrapper around a "real" implementation wherever you currently just use the implementation.